/* eslint-disable import/no-extraneous-dependencies */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import type { TInvoiceExpanded } from '@blocklet/payment-types';
import { Box, Button, CircularProgress } from '@mui/material';
import JsPDF from 'jspdf';
import { useEffect, useState } from 'react';

import { loadFont, loadImage } from './utils';
import { InvoiceTemplate } from './template';

export function Download({ data }: { data: TInvoiceExpanded }) {
  const { t } = useLocaleContext();
  const [isReady, setIsReady] = useState(false);
  const [isGenerating, setIsGenerating] = useState(false);

  useEffect(() => {
    const preload = async () => {
      try {
        const [fontLoaded] = await Promise.all([loadFont(), loadImage(window.blocklet.appLogo?.split('?')[0] || '')]);
        setIsReady(fontLoaded);
      } catch (error) {
        console.error('Resource loading failed:', error);
      }
    };
    preload();
  }, []);

  const generatePDF = async () => {
    if (!isReady || isGenerating) return;

    try {
      setIsGenerating(true);

      const element = document.getElementById('invoice-template');
      if (!element) return;
      const html2canvas = (await import(/* webpackChunkName: "html2canvas" */ 'html2canvas')).default;
      const canvas = await html2canvas(element, {
        scale: 5,
        useCORS: true,
        logging: false,
        windowWidth: 794,
        windowHeight: 1123,
        allowTaint: true,
        backgroundColor: '#ffffff',
        imageTimeout: 15000,
        removeContainer: true,
        onclone: (clonedDoc) => {
          const clonedElement = clonedDoc.getElementById('invoice-template');
          if (clonedElement) {
            clonedElement.style.position = 'relative';
            clonedElement.style.left = '0';
            clonedElement.style.transform = 'scale(1)';
            clonedElement.style.transformOrigin = 'top left';
            clonedElement.style.textRendering = 'geometricPrecision';
            (clonedElement.style as any)['-webkit-font-smoothing'] = 'antialiased';
            (clonedElement.style as any)['-moz-osx-font-smoothing'] = 'grayscale';
          }
        },
      });

      const pdf = new JsPDF({
        orientation: 'portrait',
        unit: 'pt',
        format: 'a4',
        compress: true,
        precision: 32,
        hotfixes: ['px_scaling'],
      });

      const imgWidth = canvas.width;
      const imgHeight = canvas.height;
      const pdfWidth = pdf.internal.pageSize.getWidth();
      const pdfHeight = pdf.internal.pageSize.getHeight();
      const ratio = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight);

      pdf.addImage(
        canvas.toDataURL('image/png', 1.0),
        'PNG',
        0,
        0,
        imgWidth * ratio,
        imgHeight * ratio,
        undefined,
        'FAST'
      );

      pdf.save(`${data.number}.pdf`);
    } catch (error) {
      console.error('PDF generation failed:', error);
    } finally {
      setIsGenerating(false);
    }
  };

  return (
    <div className="download-pdf">
      <Button
        variant="outlined"
        color="primary"
        size="small"
        onClick={generatePDF}
        disabled={!isReady || isGenerating}
        sx={{ borderColor: 'divider' }}>
        {isGenerating ? (
          <Box sx={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <CircularProgress size={16} sx={{ color: 'inherit' }} />
            {t('payment.customer.invoice.download')}
          </Box>
        ) : (
          t('payment.customer.invoice.download')
        )}
      </Button>
      <InvoiceTemplate data={data} t={t} />
    </div>
  );
}

export default Download;
