'use client';

import React, { useMemo, useState } from 'react';

import { useLocale } from 'next-intl';

import { pdf } from '@react-pdf/renderer';
import { FaHourglassHalf } from 'react-icons/fa';
import { FaRegFilePdf } from 'react-icons/fa6';

import CreatorTextPDFDocument from './CreatorTextPDFDocument';

type CreatorTextPdfButtonProps = {
  creatorName: string;
  sectionTitle: string;
  sectionSubtitle?: string;
  content: string;
};

const CreatorTextPdfButton: React.FC<CreatorTextPdfButtonProps> = ({
  creatorName,
  sectionTitle,
  sectionSubtitle,
  content,
}) => {
  const locale = useLocale();
  const [isGenerating, setIsGenerating] = useState(false);
  const sections = useMemo(
    () => [
      {
        title: sectionTitle,
        subtitle: sectionSubtitle,
        content,
      },
    ],
    [sectionTitle, sectionSubtitle, content]
  );

  const safeFileName = (name: string) => {
    const normalized = name
      .toLowerCase()
      .normalize('NFD') // szétszedi: á -> a +  ́
      .replace(/[\u0300-\u036f]/g, '') // leszedjük az ékezetet
      .replace(/[^a-z0-9\s-]/g, '')
      .trim()
      .replace(/\s+/g, '-');

    return normalized || 'creator';
  };

  const handleDownloadPDF = async () => {
    setIsGenerating(true);

    try {
      const blob = await pdf(
        <CreatorTextPDFDocument creatorName={creatorName} sections={sections} />
      ).toBlob();

      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `azopus.hu-${safeFileName(creatorName)}.pdf`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {
      console.error('PDF generation error:', error);
      alert(locale === 'en' ? 'Failed to generate PDF.' : 'Hiba tortent a PDF generalasa soran.');
    } finally {
      setIsGenerating(false);
    }
  };

  const label =
    locale === 'en'
      ? isGenerating
        ? 'Generating PDF...'
        : 'Download PDF'
      : isGenerating
        ? 'PDF generálása...'
        : 'PDF letöltése';

  return (
    <button
      type="button"
      onClick={handleDownloadPDF}
      aria-label={label}
      title={label}
      className="absolute right-2 top-2 inline-flex items-center justify-center text-[#eb1000] transition hover:text-mma-yellow"
    >
      {isGenerating ? (
        <span className="animate-spin text-base md:text-lg">
          <FaHourglassHalf />
        </span>
      ) : (
        <span className="text-xl md:text-3xl">
          <FaRegFilePdf />
        </span>
      )}
    </button>
  );
};

export default CreatorTextPdfButton;
