import { useEffect, useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

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

import useAuth from 'src/contexts/JWTContext';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { useDownloadBulkCertificates } from 'src/pages/dashboard/Learning/Courses/hooks/useDownloadBulkCertificates';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { formatSegmentationIds } from 'src/utils/segmentationUtils';
import { validateEmailRule } from 'src/utils/validation';

import CertificateSegmentation, {
  type CertificateSegmentationValue,
} from './CertificateSegmentation';

type UseBulkCertificatesDrawerProps = {
  courseId: number;
};

type FormValues = {
  email: string;
  segmentation: CertificateSegmentationValue;
};

export const useBulkCertificatesDrawer = ({
  courseId,
}: UseBulkCertificatesDrawerProps) => {
  const { t } = useLokaliseTranslation('learning');
  const { user } = useAuth();
  const HugoThemeProvider = useHuGoTheme();

  const downloadBulkCertificates = useDownloadBulkCertificates(courseId);

  const form = useForm<FormValues>({
    defaultValues: { email: user?.email || '', segmentation: null },
    mode: 'onChange',
  });

  const handleClose = () => {
    form.reset();
    closeDrawer();
  };

  const handleConfirm = () => {
    form.handleSubmit(({ email, segmentation }) => {
      let segmentationItemIds: number[] | undefined;
      let segmentationUserIds: number[] | undefined;

      if (segmentation !== null) {
        const ids = formatSegmentationIds(segmentation);
        segmentationItemIds = ids.segmentationItemIds?.length
          ? ids.segmentationItemIds
          : undefined;
        segmentationUserIds = ids.segmentationUserIds?.length
          ? ids.segmentationUserIds
          : undefined;
      }

      downloadBulkCertificates.mutate({
        email,
        segmentationItemIds,
        segmentationUserIds,
      });
      handleClose();
    })();
  };

  const { showDrawer, closeDrawer, open, drawer } = useDrawerV2(() => ({
    title: t('reports.bulk_certificates.title'),
    children: (
      <HugoThemeProvider>
        <FormProvider {...form}>
          <Stack sx={{ gap: 2 }}>
            <Typography variant="globalS">
              {t('reports.bulk_certificates.description')}
            </Typography>

            <CertificateSegmentation
              name="segmentation"
              courseId={courseId}
            />

            <FormInputClassic
              name="email"
              rules={{ validate: validateEmailRule }}
              inputProps={{
                label: t('general:add_email'),
                placeholder: t('general:email'),
                type: 'email',
                hasCounter: false,
              }}
            />
          </Stack>
        </FormProvider>
      </HugoThemeProvider>
    ),
    primaryButtonProps: {
      children: t('general:confirm_download'),
      loading: downloadBulkCertificates.isLoading,
      disabled: downloadBulkCertificates.isLoading,
      onClick: handleConfirm,
    },
    secondaryButtonProps: {
      children: t('general:close'),
      onClick: handleClose,
      fullWidth: true,
    },
    onClose: handleClose,
  }));

  return { drawer, showBulkCertificatesDrawer: showDrawer };
};
