import { useEffect, useRef } from 'react';
import { useFormContext } from 'react-hook-form';
import { useNavigate } from 'react-router';

import useHuSnackbar from '@material-hu/components/design-system/Snackbar';
import { useAuth } from 'src/contexts/JWTContext';
import { useMobile } from 'src/contexts/MobileContext';
import {
  downloadBlobAsFile,
  useGenerateBanbajioPDFDownload,
  generateBuroApprovalPDF,
  generateFibaCreditRequestLetterPDF,
  handleWebViewPdf,
  generateBanbajioCreditRequestLetterPDF,
} from 'src/utils/banBajio';
import { useLokaliseTranslation } from 'src/utils/i18n';

import BossSupportLetter from './BossSupportLetter';
import { banBajioRoutes } from './routes';
import { useDynamicFields } from './useDynamicFields';

// eventually will be customizable
const GENERATE_REQUEST_PDF = true;
const GENERATE_BOSS_SUPPORT_PDF = true;
const GENERATE_BURO_APPROVAL_PDF = true;

const FormPDFs = () => {
  const cartaRef = useRef<HTMLDivElement>(null);
  const { isMobile } = useMobile();
  const { t } = useLokaliseTranslation('banbajio');
  const { enqueueSnackbar } = useHuSnackbar();
  const navigate = useNavigate();
  const { user } = useAuth();
  const form = useFormContext();

  const { data: profileData } = useDynamicFields();

  const generatePDF = useGenerateBanbajioPDFDownload();

  useEffect(() => {
    const asyncDownload = async () => {
      try {
        GENERATE_REQUEST_PDF &&
          (await (profileData!.isFiba
            ? handleDownloadFibaCreditRequestLetter()
            : handleDownloadBanbajioCreditRequestLetter()));
        GENERATE_BURO_APPROVAL_PDF && (await handleDownloadBuroApprovalPDF());
        GENERATE_BOSS_SUPPORT_PDF &&
          (await generatePDF(cartaRef.current!, 'Carta Apoyo del Jefe.pdf'));
      } finally {
        enqueueSnackbar({
          title: t('DOCUMENT_GENERATED_SUCCESSFULLY'),
          description: t('DOCUMENT_GENERATED_SUCCESSFULLY_DESCRIPTION'),
          variant: 'success',
        });
        navigate(banBajioRoutes.home() + (isMobile ? '-mobile/1' : ''));
      }
    };
    asyncDownload();
  }, []);

  const handleDownloadBanbajioCreditRequestLetter = () =>
    generateAndDownloadPDF(
      t('CREDIT_APPLICATION_PDF'),
      generateBanbajioCreditRequestLetterPDF,
    );

  const handleDownloadFibaCreditRequestLetter = () =>
    generateAndDownloadPDF(
      t('CREDIT_APPLICATION_PDF'),
      generateFibaCreditRequestLetterPDF,
    );

  const handleDownloadBuroApprovalPDF = () =>
    generateAndDownloadPDF(
      t('CREDIT_BUREAU_AUTHORIZATION_LETTER'),
      generateBuroApprovalPDF,
    );

  const webViewDataRef = useRef<any[]>([]);

  const generateAndDownloadPDF = async (
    name: string,
    generateFunction: Function,
  ) => {
    const pdfDoc = await generateFunction(profileData, user!, form.getValues());
    if (isMobile) {
      const base64String = await pdfDoc.saveAsBase64();
      const docData = {
        name,
        url: `data:application/pdf;filename=generated.pdf;base64,${base64String}`,
      };
      if (webViewDataRef.current.length > 0) {
        handleWebViewPdf([...webViewDataRef.current, docData]);
      } else {
        webViewDataRef.current.push(docData);
      }
    } else {
      const pdfBytes = await pdfDoc.save();
      downloadBlobAsFile(
        new Blob([pdfBytes], { type: 'application/pdf' }),
        name,
      );
    }
  };

  return (
    <div style={{ position: 'absolute', top: '-9999px', left: '-9999px' }}>
      <BossSupportLetter ref={cartaRef} />
    </div>
  );
};

export default FormPDFs;
