import { useState } from 'react';
import { Controller, useFormContext } from 'react-hook-form';
import { useInfiniteQuery } from 'react-query';

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

import Alert from '@material-hu/components/design-system/Alert';

import { getPublicUsers } from 'src/services/users';
import { SectionsManager } from 'src/types/vacations';
import { useLokaliseTranslation } from 'src/utils/i18n';

import PeopleSelection from '../components/shared/PeopleSelection';
import { formFieldsRequestCreate } from '../constant';
import { vacationsKeys } from '../queries';

import { type RequestCreateForm } from './useRequestCreate';

type Props = {
  isEdit?: boolean;
};

const useSubstituteApprover: GetDrawerConfiguration<Props> = ({
  isEdit = false,
  open,
  closeDrawer,
}) => {
  const { t } = useLokaliseTranslation('time_off');
  const [search, setSearch] = useState('');
  const debouncedSearch = useDebounce(search);
  const form = useFormContext<RequestCreateForm>();

  const queryResult = useInfiniteQuery(
    vacationsKeys.usersList(debouncedSearch, SectionsManager.CALENDAR, false),
    ({ pageParam = 1 }) =>
      getPublicUsers({
        page: pageParam,
        limit: 30,
        search: debouncedSearch,
        excludeOfflineUsers: true,
      }),
    {
      getNextPageParam: lastPage =>
        lastPage.data.page < lastPage.data.totalPages
          ? lastPage.data.page + 1
          : undefined,
      enabled: !!open,
    },
  );

  const handleSave = async () => {
    await form.trigger(formFieldsRequestCreate.substituteApprover);

    if (form.formState.errors[formFieldsRequestCreate.substituteApprover])
      return;

    closeDrawer();
  };

  const handleClose = () => {
    setSearch('');
    if (!isEdit) {
      form.setValue(formFieldsRequestCreate.substituteApprover, null);
    }
    closeDrawer();
  };

  return {
    title: t('substitute_approver.select'),
    children: (
      <Controller
        control={form.control}
        name={formFieldsRequestCreate.substituteApprover}
        rules={{
          validate: value => {
            if (!value) {
              return t('substitute_approver.required');
            }
            return true;
          },
        }}
        render={() => (
          <PeopleSelection
            selectionMode="single"
            queryResult={queryResult}
            search={search}
            onSearchChange={setSearch}
            fieldName={formFieldsRequestCreate.substituteApprover}
          />
        )}
      />
    ),
    footer: form.formState.errors[
      formFieldsRequestCreate.substituteApprover
    ] ? (
      <Alert
        severity="error"
        title={
          form.formState.errors[formFieldsRequestCreate.substituteApprover]
            ?.message as string
        }
      ></Alert>
    ) : null,
    primaryButtonProps: { children: t('general:select'), onClick: handleSave },
    secondaryButtonProps: {
      children: t('general:cancel'),
      onClick: handleClose,
    },
    onClose: handleClose,
  };
};

export default useSubstituteApprover;
