import {
  type FieldValues,
  FormProvider,
  useForm,
  useWatch,
} from 'react-hook-form';
import { useTranslation } from 'react-i18next';

import { useDrawerV2 } from '@hooks/useDrawerV2';

import CriteriaCollaboratorsReachFooter from './CriteriaCollaboratorsReachFooter';
import CriteriaDrawerContent from './CriteriaDrawerContent';
import { type CriteriaDrawerProps, type UseCriteriaDrawerProps } from './types';

const useCriteriaDrawer = <TValues extends FieldValues>({
  defaultValues,
  collaboratorsReach,
  validate,
}: UseCriteriaDrawerProps<TValues>) => {
  const { t } = useTranslation('material_hu_only');

  const form = useForm<TValues>({
    defaultValues,
  });

  const formValues = useWatch({ control: form.control }) as TValues;
  const isInvalid = validate ? !validate(formValues) : false;

  const { handleSubmit, reset } = form;

  const {
    drawer: criteriaDrawer,
    showDrawer: showCriteriaDrawer,
    closeDrawer: closeCriteriaDrawer,
  } = useDrawerV2<CriteriaDrawerProps<TValues>>(
    ({
      onClose,
      onConfirm,
      title,
      description,
      disabled = false,
      loading = false,
      children,
      ...args
    }) => {
      const closeDrawer = () => {
        onClose?.();
        closeCriteriaDrawer();
        reset();
      };

      const submit = handleSubmit(values => {
        onConfirm(values);
        closeCriteriaDrawer();
        reset();
      });

      return {
        ...args,
        component: 'form',
        onSubmit: submit,
        onClose: closeDrawer,
        title,
        primaryButtonProps: {
          children: t('audience.confirm'),
          type: 'submit',
          disabled: disabled || isInvalid,
          loading,
        },
        secondaryButtonProps: {
          children: t('audience.cancel'),
          onClick: closeDrawer,
          disabled,
        },
        footer: collaboratorsReach ? (
          <CriteriaCollaboratorsReachFooter
            collaboratorsReach={collaboratorsReach}
            onSelectedCollaboratorsDismiss={closeDrawer}
          />
        ) : undefined,
        children: (
          <CriteriaDrawerContent description={description}>
            {children}
          </CriteriaDrawerContent>
        ),
      };
    },
  );

  return {
    criteriaDrawer: <FormProvider {...form}>{criteriaDrawer}</FormProvider>,
    showCriteriaDrawer: showCriteriaDrawer,
    closeCriteriaDrawer: closeCriteriaDrawer,
    criteriaForm: form,
  };
};

export default useCriteriaDrawer;
