import { useFormContext } from 'react-hook-form';
import { useMutation } from 'react-query';

import Stack from '@material-hu/mui/Stack';

import Button from '@material-hu/components/design-system/Buttons/Button';
import FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
import useSnackbar from '@material-hu/components/design-system/Snackbar';

import useGeneralError from 'src/hooks/useGeneralError';
import useRules from 'src/hooks/useRules';
import { createExternalUserReviewers } from 'src/pages/dashboard/performance/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

export type ExternalUserReviewerFormProps = {
  onCancel: () => void;
};

const ExternalUserReviewerForm = ({
  onCancel,
}: ExternalUserReviewerFormProps) => {
  const { t } = useLokaliseTranslation(['performance']);
  const { watch, handleSubmit, reset, formState } = useFormContext();
  const { enqueueSnackbar } = useSnackbar();
  const showGeneralError = useGeneralError();

  const { mutate, isLoading } = useMutation(
    () =>
      createExternalUserReviewers({
        firstName: watch('firstName'),
        lastName: watch('lastName'),
        email: watch('email'),
      }),
    {
      onSuccess: () => {
        enqueueSnackbar({
          title: t(
            'form.external_review.create_external_user_reviewer_success',
          ),
          variant: 'success',
        });
        reset();
        onCancel();
      },
      // biome-ignore lint/suspicious/noExplicitAny: out of scope
      onError: (err: any) => {
        if (
          err?.response?.data?.code ===
          'REVIEW_CYCLE_EXTERNAL_REVIEWER_EMAIL_ALREADY_EXISTS'
        ) {
          showGeneralError(
            err,
            t('form.external_review.create_external_user_reviewer_error'),
          );
          return;
        }

        showGeneralError(err);
      },
    },
  );

  const submit = () => {
    mutate();
  };

  const emailRules = useRules({
    requiredWithMessage: true,
    email: true,
  });

  const firstNameRules = useRules({
    requiredWithMessage: true,
  });

  return (
    <Stack sx={{ height: '100%' }}>
      <Stack sx={{ overflow: 'auto', flex: 1 }}>
        <FormInputClassic
          name="firstName"
          rules={firstNameRules}
          inputProps={{ label: t('general:name'), maxLength: 255 }}
        />
        <FormInputClassic
          name="lastName"
          rules={firstNameRules}
          inputProps={{ label: t('general:last_name'), maxLength: 255 }}
        />
        <FormInputClassic
          name="email"
          rules={emailRules}
          inputProps={{ label: t('general:email') }}
        />
      </Stack>
      <Stack
        sx={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          gap: 1,
          pt: 1,
        }}
      >
        <Button
          onClick={onCancel}
          fullWidth
        >
          {t('general:cancel')}
        </Button>
        <Button
          disabled={!formState.isDirty}
          onClick={handleSubmit(submit)}
          loading={isLoading}
          variant="contained"
          fullWidth
        >
          {t('general:accept')}
        </Button>
      </Stack>
    </Stack>
  );
};

export default ExternalUserReviewerForm;
