import React, {useCallback, useEffect} from 'react';
import {View} from 'react-native';
import {useController, useFormContext} from 'react-hook-form';
import {Checkbox, SelectionCard, Typography} from '@components';
import {FormOption, FormValue} from '@components/DynamicForm/interfaces';
import {FORM_STYLE} from '@components/DynamicForm/styles';
import {useTheme} from '@shared/theme';

interface Props {
  options: FormOption[];
  disabled?: boolean;
  initialValue?: number[];
  name: string;
  onChangeInput?: (value: FormValue) => void;
}

function FormMultipleChoice({
  options,
  disabled,
  initialValue,
  name,
  onChangeInput,
}: Props) {
  const {theme} = useTheme();

  const {control} = useFormContext();
  const {
    field: {onChange, value = []},
    fieldState: {error},
  } = useController({control, name});

  const onToggle = useCallback(
    (id: number) => () => {
      const exists = value.includes(id);
      const newValue = exists
        ? value.filter((v: number) => v !== id)
        : [...value, id];
      onChange(newValue);
      onChangeInput?.(newValue);
    },
    [value, onChange, onChangeInput],
  );

  useEffect(() => {
    if (initialValue?.length) {
      onChange(initialValue);
    }
  }, [initialValue, onChange]);

  return (
    <View style={FORM_STYLE.listContainer}>
      {options.map(option => {
        const isSelected = value.includes(option.id);
        return (
          <SelectionCard
            isSelected={isSelected}
            key={option.id}
            style={FORM_STYLE.selectionContainer}
            onPress={onToggle(option.id)}
            disabled={disabled}>
            <Checkbox
              key={option.id}
              title={option.label}
              checked={isSelected}
              onPress={onToggle(option.id)}
              disabled={disabled}
            />
          </SelectionCard>
        );
      })}
      {error && (
        <Typography variant="xs" color={theme.text.feedback.error}>
          {error.message?.toString()}
        </Typography>
      )}
    </View>
  );
}

export default FormMultipleChoice;
