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

import { useDebounce } from '@material-hu/hooks/useDebounce';
import { type GetDrawerConfiguration } from '@material-hu/hooks/useDrawerV2';
import Typography from '@material-hu/mui/Typography';

import { type SectionsManager } from 'src/types/vacations';
import { useLokaliseTranslation } from 'src/utils/i18n';

import PeopleSelection, {
  type SelectionMode,
} from '../components/shared/PeopleSelection';

import useInfinitePeople from './useInfinitePeople';

type Props = {
  type: SectionsManager;
  closeDrawer: () => void;
  open: boolean;
  isManagerView?: boolean;
  fieldName?: string;
  selectionMode?: SelectionMode;
};

export const usePeopleSelectionDrawer: GetDrawerConfiguration<Props> = ({
  type,
  closeDrawer,
  open,
  isManagerView = true,
  fieldName = 'users',
}) => {
  const [search, setSearch] = useState('');
  const debouncedSearch = useDebounce(search);
  const form = useFormContext();
  const { t } = useLokaliseTranslation('time_off');

  const watchFields = isManagerView ? ['visibility', fieldName] : [fieldName];
  const watchedValues = useWatch({ control: form.control, name: watchFields });
  const [visibility] = isManagerView ? watchedValues : [undefined];

  const queryResult = useInfinitePeople(
    {
      search: debouncedSearch,
      type,
      isManagerView,
      visibility,
    },
    {
      enabled: open,
    },
  );

  const onClose = useCallback(() => {
    closeDrawer();
    form.setValue(fieldName, []);
  }, [closeDrawer, form, fieldName]);

  return {
    children: (
      <PeopleSelection
        fieldName={fieldName}
        search={search}
        onSearchChange={setSearch}
        queryResult={queryResult}
        headerContent={
          isManagerView && (
            <Typography
              sx={{ fontWeight: 'fontWeightRegular', variant: 'globalXS' }}
            >
              {t('users_visibility_helper')}
            </Typography>
          )
        }
      />
    ),
    title: t('general:select_people'),
    primaryButtonProps: { children: t('general:select'), onClick: closeDrawer },
    secondaryButtonProps: { children: t('general:cancel'), onClick: onClose },
    onClose,
  };
};

export default usePeopleSelectionDrawer;
