import { useTranslation } from 'react-i18next';

import useCriteriaDrawer from '@composed-components/audience/hooks/useCriteriaDrawer';
import FormConditionGroup from '@composed-components/ConditionGroup/form';
import { type DefaultItemType } from '@composed-components/ConditionLine/types';
import { merge } from 'lodash';

import {
  type SegmentationCriteriaDrawerProps,
  type SegmentationCriteriaValues,
  type UseSegmentationCriteriaDrawerProps,
} from './types';
import { isSegmentationCriteriaEmpty } from './utils';

const useSegmentationCriteriaDrawer = <
  FieldItemType extends DefaultItemType,
  ValueItemType extends DefaultItemType,
>({
  defaultValues,
  collaboratorsReach,
  validate,
}: UseSegmentationCriteriaDrawerProps<FieldItemType, ValueItemType>) => {
  const { t } = useTranslation('material_hu_only');
  const {
    criteriaDrawer,
    showCriteriaDrawer,
    closeCriteriaDrawer,
    criteriaForm,
  } = useCriteriaDrawer<
    SegmentationCriteriaValues<FieldItemType, ValueItemType>
  >({
    defaultValues,
    collaboratorsReach: collaboratorsReach
      ? {
          ...collaboratorsReach,
          isFormEmpty: isSegmentationCriteriaEmpty,
        }
      : undefined,
    validate: values => {
      const callerValid = validate ? validate(values) : true;
      return !isSegmentationCriteriaEmpty(values) && callerValid;
    },
  });

  const showSegmentationCriteriaDrawer = (
    props: SegmentationCriteriaDrawerProps<FieldItemType, ValueItemType>,
  ) => {
    const { showInfo = true, ...restProps } = props;
    showCriteriaDrawer({
      ...restProps,
      title: t('audience.segmentation_groups_title'),
      description: t(
        showInfo
          ? 'audience.segmentation_criteria_description'
          : 'audience.segmentation_groups_description',
      ),
      children: (
        <FormConditionGroup
          name="conditions"
          inputProps={merge(
            {
              disabled: restProps.disabled,
            },
            restProps.inputProps,
          )}
        />
      ),
    });
  };

  return {
    showSegmentationCriteriaDrawer,
    closeSegmentationCriteriaDrawer: closeCriteriaDrawer,
    segmentationCriteriaDrawer: criteriaDrawer,
    segmentationCriteriaForm: criteriaForm,
  };
};

export default useSegmentationCriteriaDrawer;
