import React, {useCallback} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {Typography} from '@components';
import {
  Answer,
  Option,
  QuestionSubtype,
  QuestionType,
} from '@modules/peopleExperience/interfaces';
import CheckboxInput from '@modules/peopleExperience/components/CheckboxInput';
import Input from '@modules/peopleExperience/components/Input';
import TextInput from '@modules/peopleExperience/components/TextInput';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

interface Props {
  error?: boolean;
  questionId: string;
  title: string;
  required: boolean;
  type: QuestionType;
  subType: Nullable<QuestionSubtype>;
  options: Option[];
  onChangeValue?: (v: unknown) => void;
  value: unknown;
  disabled?: boolean;
  topText?: string;
}

function FormInput({
  error,
  questionId,
  title,
  required,
  type,
  options,
  onChangeValue,
  value,
  disabled,
  topText,
  subType,
}: Props) {
  const {t} = useTranslation();
  const {theme} = useTheme();

  const renderInput = useCallback(() => {
    const props = {
      questionId,
      options,
      onChangeValue: onChangeValue as (v?: Answer) => void,
      disabled,
    };

    switch (type) {
      case QuestionType.CHECKBOX:
      case QuestionType.MULTIPLE_CHOICE:
        return (
          <CheckboxInput
            {...props}
            {...(type === QuestionType.MULTIPLE_CHOICE && {radio: true})}
            value={value as Nullable<number[] | number>}
          />
        );
      case QuestionType.RATING:
        return (
          <Input
            {...props}
            value={value as Nullable<number>}
            subType={subType}
            type={type}
          />
        );
      case QuestionType.TEXT:
        return <TextInput {...props} value={value as string} />;
      default:
        return null;
    }
  }, [disabled, onChangeValue, options, questionId, type, value, subType]);

  return (
    <View
      style={[
        styles.formInput,
        {backgroundColor: theme.background.elements.default},
      ]}>
      <View>
        {topText && (
          <Typography variant="xxs" color={theme.text.neutral.lighter}>
            {topText}
          </Typography>
        )}
        <Typography
          weight="semiBold"
          color={
            error ? theme.text.feedback.error : theme.text.neutral.default
          }>
          {title}
        </Typography>
        {required && (
          <Typography
            variant="xs"
            color={
              error ? theme.text.feedback.error : theme.text.neutral.lighter
            }>{`*${t('people_experience.mandatory_question')}`}</Typography>
        )}
      </View>
      <View>{renderInput()}</View>
    </View>
  );
}

export default FormInput;
