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

import {
  type ConditionLineValues,
  type DefaultItemType,
} from '@composed-components/ConditionLine/types';

import {
  type ConditionGroupValues,
  type FormConditionGroupProps,
} from './types';
import ConditionGroup from './index';

const FormConditionGroup = <
  FieldItemType extends DefaultItemType,
  ValueItemType extends DefaultItemType,
>({
  name,
  inputProps,
}: FormConditionGroupProps<FieldItemType, ValueItemType>) => {
  const { control } = useFormContext();

  const { fields, replace } = useFieldArray({ name, control });

  const value = fields as unknown as ConditionLineValues<
    FieldItemType,
    ValueItemType
  >[];

  const handleChange = (
    newValues: ConditionGroupValues<FieldItemType, ValueItemType>,
  ) => {
    replace(newValues);
  };

  return (
    <ConditionGroup
      {...inputProps}
      value={value}
      onChange={handleChange}
    />
  );
};

export type { FormConditionGroupProps };

export default FormConditionGroup;
