'use client';

import { useCallback, useState } from 'react';
import type { ReactElement } from 'react';

import { useTranslations } from 'next-intl';

import { type DocumentProps, pdf } from '@react-pdf/renderer';

type DownloadPdfOptions = {
  errorMessage?: string;
  onError?: (error: unknown) => void;
  showAlertOnError?: boolean;
};

export const usePdfDownload = (options?: DownloadPdfOptions) => {
  const [isPdfLoading, setIsPdfLoading] = useState(false);
  const [pdfError, setPdfError] = useState<unknown>(null);
  const t = useTranslations('common');

  const errorMessage = options?.errorMessage;
  const onError = options?.onError;
  const showAlertOnError = options?.showAlertOnError ?? true;

  const downloadPdf = useCallback(
    async (pdfDocument: ReactElement<DocumentProps>, fileName: string) => {
      if (isPdfLoading) return false;

      setIsPdfLoading(true);
      setPdfError(null);

      let url: string | null = null;
      let anchor: HTMLAnchorElement | null = null;

      try {
        const blob = await pdf(pdfDocument).toBlob();
        url = window.URL.createObjectURL(blob);
        anchor = document.createElement('a');
        anchor.href = url;
        anchor.download = fileName;
        document.body.appendChild(anchor);
        anchor.click();

        return true;
      } catch (error) {
        setPdfError(error);
        console.error('PDF generation error:', error);
        onError?.(error);

        if (showAlertOnError) {
          window.alert(errorMessage ?? t('pdfGenerationError'));
        }

        return false;
      } finally {
        if (anchor?.parentNode) {
          anchor.parentNode.removeChild(anchor);
        }
        if (url) {
          window.URL.revokeObjectURL(url);
        }
        setIsPdfLoading(false);
      }
    },
    [errorMessage, isPdfLoading, onError, showAlertOnError, t]
  );

  return {
    downloadPdf,
    pdfError,
    isPdfLoading,
  };
};
