import { FC, useEffect } from 'react';
import { useFormContext } from 'react-hook-form';

import { useStackStepForms } from 'src/contexts/StackStepFormsContext';
import {
  buildOptionsToRadioButton,
  modifyStackStepForms,
} from 'src/utils/form';

import FormRadioGroup from 'src/components/FormInputs/FormRadioGroup';

export type MultipleRadioButtonProps = {
  name?: string;
  options?: any[];
  required?: boolean;
  answer?: number;
  answerInput?: { answer: any };
  formFilled?: boolean;
  indexAsValue?: boolean;
};

export const MultipleRadioButton: FC<MultipleRadioButtonProps> = props => {
  const {
    name,
    options,
    required,
    answer,
    answerInput,
    formFilled,
    indexAsValue = false,
  } = props;

  const { getValues } = useFormContext();

  const { stackStepForms, hasBranching, stepsList } = useStackStepForms();

  useEffect(() => {
    const valueInput = getValues(name);

    if (hasBranching && valueInput) {
      modifyStackStepForms(options, valueInput, stackStepForms, stepsList);
    }
  }, []);

  const getDefaultValue = () => {
    if (indexAsValue) return answer;
    if (answerInput) {
      return answerInput?.answer?.find(element => element.checked)?.description;
    }
    return null;
  };

  const handleChangeSkipStep = e => {
    if (!hasBranching) return;
    modifyStackStepForms(options, e.target.value, stackStepForms, stepsList);
  };

  return (
    <FormRadioGroup
      indexAsValue={indexAsValue}
      name={name}
      disabled={formFilled}
      options={buildOptionsToRadioButton(options)}
      rules={{ required: required && !formFilled }}
      defaultValue={getDefaultValue()}
      onChangeSkipStep={handleChangeSkipStep}
    />
  );
};

export default MultipleRadioButton;
