"use client";

import { useState } from "react";
import { FaFilePdf } from "react-icons/fa6";
import toast from "react-hot-toast";

import Button from "@/components/common/button";
import { useClientPortalAuth } from "@/components/pages/client/participant-list/common/client-portal-auth-context";
import { downloadScreenerPdfFromPortal } from "@/services/client/participant-list/portal-actions";

function base64ToBlob(base64: string, type: string): Blob {
  const binary = atob(base64);
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i += 1) {
    bytes[i] = binary.charCodeAt(i);
  }
  return new Blob([bytes], { type });
}

function DownloadScreenerButton() {
  const { auth, handlePortalStatus } = useClientPortalAuth();
  const [isDownloading, setIsDownloading] = useState(false);

  const handleDownload = async () => {
    if (!auth) return;
    setIsDownloading(true);
    try {
      const result = await downloadScreenerPdfFromPortal(auth);
      if (!result.ok) {
        if (handlePortalStatus(result.status)) return;
        if (result.status === 404) {
          toast.error("The screener isn't available for this project yet.");
        } else {
          toast.error("Failed to download the screener PDF.");
        }
        return;
      }

      const blob = base64ToBlob(result.base64, "application/pdf");
      const objectUrl = URL.createObjectURL(blob);
      const anchor = document.createElement("a");
      anchor.href = objectUrl;
      anchor.download = result.filename;
      document.body.appendChild(anchor);
      anchor.click();
      anchor.remove();
      URL.revokeObjectURL(objectUrl);

      toast.success("Screener downloaded.");
    } catch {
      toast.error("Failed to download the screener PDF.");
    } finally {
      setIsDownloading(false);
    }
  };

  return (
    <Button
      btnLabel="Download screener"
      customVariant="transparent-black"
      isLoading={isDownloading}
      size="sm"
      startContent={!isDownloading && <FaFilePdf className="h-3.5 w-3.5" />}
      onClick={handleDownload}
    />
  );
}

export default DownloadScreenerButton;
