"use client";

import { useState } from "react";
import { FaFileExcel } 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 { useTimezone } from "@/components/pages/client/participant-list/common/timezone-context";
import { exportSchedulingXlsxFromPortal } 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 index = 0; index < binary.length; index += 1) {
    bytes[index] = binary.charCodeAt(index);
  }
  return new Blob([bytes], { type });
}

function ExportSchedulingButton() {
  const { timezone } = useTimezone();
  const { auth, handlePortalStatus } = useClientPortalAuth();
  const [isExporting, setIsExporting] = useState(false);

  const handleExport = async () => {
    if (!auth) return;
    setIsExporting(true);
    try {
      const result = await exportSchedulingXlsxFromPortal(auth, timezone);
      if (!result.ok) {
        if (handlePortalStatus(result.status)) return;
        toast.error("Failed to export scheduling table.");
        return;
      }

      const blob = base64ToBlob(
        result.base64,
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      );
      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("Scheduling table exported.");
    } catch {
      toast.error("Failed to export scheduling table.");
    } finally {
      setIsExporting(false);
    }
  };

  return (
    <Button
      btnLabel="Export sessions"
      customVariant="transparent-black"
      isLoading={isExporting}
      size="sm"
      startContent={!isExporting && <FaFileExcel className="h-3.5 w-3.5" />}
      onClick={handleExport}
    />
  );
}

export default ExportSchedulingButton;
