import { useTranslation } from 'react-i18next';

import useCriteriaDrawer from '@composed-components/audience/hooks/useCriteriaDrawer';
import { useTheme } from '@mui/material';
import { merge } from 'lodash';

import IndividualSelectionContent from './content';
import { IndividualCriteriaProvider } from './context';
import {
  type IndividualCriteriaDrawerProps,
  type IndividualCriteriaValues,
  type UseIndividualCriteriaDrawerProps,
} from './types';
import { isIndividualCriteriaEmpty } from './utils';

const useIndividualCriteriaDrawer = ({
  defaultValues,
  inputProps,
  collaboratorsReach,
  validate,
}: UseIndividualCriteriaDrawerProps) => {
  const { palette } = useTheme();
  const { t } = useTranslation('material_hu_only');
  const {
    criteriaDrawer,
    showCriteriaDrawer,
    closeCriteriaDrawer,
    criteriaForm,
  } = useCriteriaDrawer<IndividualCriteriaValues>({
    defaultValues,
    collaboratorsReach: collaboratorsReach
      ? {
          ...collaboratorsReach,
          isFormEmpty: isIndividualCriteriaEmpty,
        }
      : undefined,
    validate,
  });

  const mergedInputProps = merge(
    {
      sx: {
        overflow: 'hidden',
        backgroundColor: palette.new.background.elements.grey,
      },
      slotProps: {
        search: { placeholder: t('audience.search_placeholder') },
        emptyStateCard: {
          title: t('audience.no_collaborators_match_title'),
          description: t('audience.no_collaborators_match_description'),
        },
        selectAllCheckbox: {
          label: t('audience.select_all'),
        },
      },
    },
    inputProps,
  );

  const showIndividualCriteriaDrawer = (
    props: IndividualCriteriaDrawerProps,
  ) => {
    showCriteriaDrawer({
      ...props,
      title: t('audience.specific_collaborators_title'),
      description: t('audience.specific_collaborators_description'),
      children: <IndividualSelectionContent />,
    });
  };

  return {
    showIndividualCriteriaDrawer,
    closeIndividualCriteriaDrawer: closeCriteriaDrawer,
    individualCriteriaDrawer: (
      <IndividualCriteriaProvider value={mergedInputProps}>
        {criteriaDrawer}
      </IndividualCriteriaProvider>
    ),
    individualCriteriaForm: criteriaForm,
  };
};

export default useIndividualCriteriaDrawer;
