import { useState } from "preact/hooks";

interface ResumeDownloadButtonProps {
  className?: string;
}

export default function ResumeDownloadButton({
  className = "",
}: ResumeDownloadButtonProps) {
  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?t=${Date.now()}`);

      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 font-bold rounded-full inline-flex items-center gap-2 text-sm sm:text-base ${
          isLoading
            ? "text-primary border-2 border-primary"
            : ""
        }`}
      >
        {isLoading ? (
          <>
            <span class="loading loading-spinner"></span>
            Generating PDF...
          </>
        ) : (
          <>Download Resume</>
        )}
      </button>
      {error && <div class="mt-2 text-error text-sm">{error}</div>}
    </div>
  );
}
