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

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

function FormCheckbox({
  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 === option.id;
        return (
          <SelectionCard
            isSelected={isSelected}
            key={option.id}
            style={FORM_STYLE.selectionContainer}
            onPress={onSelect(option.id)}
            disabled={disabled}>
            <RadioButton
              title={option.label}
              checked={isSelected}
              onPress={onSelect(option.id)}
              disabled={disabled}
            />
          </SelectionCard>
        );
      })}
      {error && (
        <Typography variant="xs" color={theme.text.feedback.error}>
          {error.message?.toString()}
        </Typography>
      )}
    </View>
  );
}

export default FormCheckbox;
