import { FC } from 'react';
import { useFormContext } from 'react-hook-form';
import { useQuery } from 'react-query';
import { useParams } from 'react-router';

import HuFormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
import HuCircularProgress from '@material-hu/components/design-system/ProgressIndicators/Spinner';
import HuFormSwitcher from '@material-hu/components/design-system/Switcher/form';

import useRules from 'src/hooks/useRules';
import { getEventUserStats } from 'src/services/events';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { eventsKeys } from '../../queries';

export const UsersLimitForm: FC = () => {
  const { id } = useParams();
  const eventId = Number(id);
  const { watch } = useFormContext();
  const { t } = useLokaliseTranslation('events');
  const { locationType, limitUsers, location } = watch();

  const { data, isLoading } = useQuery(
    eventsKeys.eventInvitations(eventId),
    () => getEventUserStats(eventId),
    {
      enabled: !!id && !!locationType.presencial && !!limitUsers && !!location,
      select: r => r.data,
    },
  );

  const rules = useRules({
    onlyNumber: true,
    validateMinValueAllowed: data?.accepted || 1,
    requiredWithMessage: true,
  });

  const eventHasLocation = locationType.presencial;
  return (
    <>
      <HuFormSwitcher
        name="limitUsers"
        switcherProps={{
          title: t('CREATE_EVENT_FORM.WITH_MAX_GUESTS_TITLE'),
          description: t('CREATE_EVENT_FORM.WITH_MAX_GUESTS_DESCRIPTION'),
          sx: { mt: 2 },
          disabled: !location,
        }}
      />
      {isLoading && <HuCircularProgress centered />}
      {limitUsers && eventHasLocation && !isLoading && (
        <HuFormInputClassic
          inputProps={{
            label: t('CREATE_EVENT_FORM.WITH_MAX_GUESTS_TITLE'),
            sx: { mt: 2 },
          }}
          name="maxInvitedUsers"
          rules={rules}
        />
      )}
    </>
  );
};

export default UsersLimitForm;
