import { useState } from "preact/hooks";

interface PdfDownloadButtonProps {
  className?: string;
}

export default function PdfDownloadButton({
  className = "",
}: PdfDownloadButtonProps) {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleDownload = async () => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch("/api/resume/pdf");

      if (!response.ok) {
        throw new Error(
          `Failed to generate PDF: ${response.status} ${response.statusText}`,
        );
      }

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);

      // Create a temporary link element and trigger download
      const link = document.createElement("a");
      link.href = url;
      link.download = "Atridad_Lahiji_Resume.pdf";
      document.body.appendChild(link);
      link.click();

      // Clean up
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (err) {
      console.error("Error downloading PDF:", err);
      setError(err instanceof Error ? err.message : "Failed to download PDF");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div class="text-center mb-6 sm:mb-8">
      <button
        onClick={handleDownload}
        disabled={isLoading}
        class={`btn btn-primary inline-flex items-center gap-2 text-sm sm:text-base ${className}`}
      >
        {isLoading ? (
          <>
            <span class="loading loading-spinner"></span>
            Generating PDF...
          </>
        ) : (
          <>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="1em"
              height="1em"
              viewBox="0 0 24 24"
              fill="currentColor"
            >
              <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z" />
            </svg>
            Generate PDF Resume
          </>
        )}
      </button>
      {error && <div class="mt-2 text-error text-sm">{error}</div>}
    </div>
  );
}
