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

import useIndividualCriteriaDrawer from '@composed-components/audience/hooks/useIndividualCriteriaDrawer';
import useSegmentationCriteriaDrawer from '@composed-components/audience/hooks/useSegmentationCriteriaDrawer';
import { emptyCondition } from '@composed-components/ConditionGroup/constants';
import {
  type ConditionLineValues,
  type DefaultItemType,
} from '@composed-components/ConditionLine/types';
import { useDebounce } from '@hooks/useDebounce';

import { type AudienceFormValues, type CriteriaSelectorProps } from '../types';

const useAudienceDrawers = <
  FieldItemType extends DefaultItemType = DefaultItemType,
  ValueItemType extends DefaultItemType = DefaultItemType,
>({
  segmentationDrawerProps,
  individualDrawerProps,
}: CriteriaSelectorProps<FieldItemType, ValueItemType>) => {
  const [search, setSearch] = useState('');
  const debouncedSearch = useDebounce(search);

  const { watch, setValue, getValues } =
    useFormContext<AudienceFormValues<FieldItemType, ValueItemType>>();

  const criterias = watch('criterias') ?? [];

  const { inputProps: segmentationInputProps, ...segmentationHookProps } =
    segmentationDrawerProps;

  const typedEmptyCondition = emptyCondition as ConditionLineValues<
    FieldItemType,
    ValueItemType
  >;

  const {
    segmentationCriteriaDrawer,
    showSegmentationCriteriaDrawer,
    segmentationCriteriaForm,
  } = useSegmentationCriteriaDrawer<FieldItemType, ValueItemType>({
    defaultValues: { conditions: [typedEmptyCondition] },
    ...segmentationHookProps,
  });

  const {
    inputProps: { useUsersQuery, ...restIndividualInputProps },
    ...restIndividualDrawerProps
  } = individualDrawerProps;

  const usersQuery = useUsersQuery(debouncedSearch);

  const {
    individualCriteriaDrawer,
    showIndividualCriteriaDrawer,
    individualCriteriaForm,
  } = useIndividualCriteriaDrawer({
    defaultValues: { userIds: new Set(), search: '' },
    inputProps: { ...restIndividualInputProps, usersQuery },
    ...restIndividualDrawerProps,
  });

  useEffect(() => {
    const subscription = individualCriteriaForm.watch(formValues => {
      setSearch(formValues.search ?? '');
    });
    return () => subscription.unsubscribe();
  }, [individualCriteriaForm]);

  return {
    criterias,
    setValue,
    getValues,
    typedEmptyCondition,
    segmentationInputProps,
    segmentationCriteriaDrawer,
    showSegmentationCriteriaDrawer,
    segmentationCriteriaForm,
    individualCriteriaDrawer,
    showIndividualCriteriaDrawer,
    individualCriteriaForm,
  };
};

export default useAudienceDrawers;
