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

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

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

import useAuth from 'src/contexts/JWTContext';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { type DownloadReportFnParams } from 'src/pages/dashboard/Learning/Courses/types';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { validateEmailRule } from 'src/utils/validation';

import { UserFields } from 'src/components/ReportFilter/constants';

import { SegmentationFields } from './SegmentationFields';

export type DownloadReportFormValues = {
  includeGroups: boolean;
  includedGroups: number[];
  includeUserFields: boolean;
  includedUserFields: string[];
  email: string;
};

export type DownloadReportsModalProps = {
  onClose: () => void;
  onDownloadReport: (params: DownloadReportFnParams) => void;
  loading: boolean;
  isBulkCertificates?: boolean;
};

const DownloadReportsModal = ({
  onClose,
  onDownloadReport,
  loading,
  isBulkCertificates = false,
}: DownloadReportsModalProps) => {
  const HugoThemeProvider = useHuGoTheme();
  const { user } = useAuth();
  const { t } = useLokaliseTranslation('learning');

  const form = useForm<DownloadReportFormValues>({
    defaultValues: {
      includeGroups: false,
      includedGroups: [],
      includeUserFields: false,
      includedUserFields: [UserFields.COMPLETE_NAME],
      email: user?.email || '',
    },
  });

  const [
    includeGroups,
    includedGroups,
    includeUserFields,
    includedUserFields,
    email,
  ] = useWatch({
    control: form.control,
    name: [
      'includeGroups',
      'includedGroups',
      'includeUserFields',
      'includedUserFields',
      'email',
    ],
  });

  const onDownloadReportHandler = () => {
    form.handleSubmit(() => {
      onDownloadReport({
        email,
        includeGroups: includeGroups ? includedGroups : [],
        includeUserFields: includeUserFields ? includedUserFields : [],
      });
      onClose();
    })();
  };

  const dialogTitle = isBulkCertificates
    ? t('reports.bulk_certificates.title')
    : t('reports.downloads.results');

  return (
    <HugoThemeProvider>
      <Dialog
        onClose={onClose}
        title={dialogTitle}
        body={
          <FormProvider {...form}>
            <Stack sx={{ gap: 2 }}>
              {!isBulkCertificates && <SegmentationFields />}
              {isBulkCertificates && (
                <Typography variant="globalS">
                  {t('reports.bulk_certificates.description')}
                </Typography>
              )}
              <FormInputClassic
                name="email"
                rules={{ validate: validateEmailRule }}
                inputProps={{
                  label: t('general:add_email'),
                  placeholder: t('general:email'),
                  type: 'email',
                  hasCounter: false,
                }}
              />
            </Stack>
          </FormProvider>
        }
        primaryButtonProps={{
          children: t('general:confirm_download'),
          onClick: onDownloadReportHandler,
          disabled: !form.formState.isValid || loading,
          loading,
        }}
        secondaryButtonProps={{
          children: t('general:cancel'),
          onClick: onClose,
        }}
      />
    </HugoThemeProvider>
  );
};

export default DownloadReportsModal;
