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

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

function FormRating({
  options,
  disabled,
  initialValue,
  name,
  onChangeInput,
}: Props) {
  const {theme} = useTheme();
  const {control} = useFormContext();
  const {
    field: {onChange, value},
    fieldState: {error},
  } = useController({control, name});

  const onSelect = useCallback(
    (id: number) => () => {
      onChange(id);
      onChangeInput?.(id);
    },
    [onChange, onChangeInput],
  );

  useEffect(() => {
    if (typeof initialValue === 'number') {
      onSelect(initialValue)();
    }
  }, [initialValue, onSelect]);

  return (
    <View style={FORM_STYLE.listContainer}>
      {options.map(option => {
        const isSelected = value?.toString() === option.id.toString();
        return (
          <SelectionCard
            key={option.id}
            onPress={onSelect(option.id)}
            isSelected={isSelected}
            style={FORM_STYLE.selectionContainer}
            disabled={disabled}>
            <Typography
              variant="m"
              weight="semiBold"
              color={
                disabled
                  ? theme.text.neutral.lighter
                  : theme.text.neutral.default
              }>
              {option.label}
            </Typography>
          </SelectionCard>
        );
      })}
      {error && (
        <Typography variant="xs" color={theme.text.feedback.error}>
          {error.message?.toString()}
        </Typography>
      )}
    </View>
  );
}

export default FormRating;
