import { useCallback, useState } from "react";
import { Download } from "lucide-react";
import type { Person } from "@/data/mockApplications";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { downloadApplicationBackupArchive } from "@/lib/applicationBackupDownload";
import { cn } from "@/lib/utils";

type Props = {
  applicationId: string;
  author?: Pick<Person, "email" | "name"> | null;
  /** Full label (e.g. review header); default compact icon in tables */
  variant?: "full" | "compact";
  className?: string;
};

export function ApplicationBackupDownloadButton({
  applicationId,
  author,
  variant = "full",
  className,
}: Props) {
  const [busy, setBusy] = useState(false);
  const run = useCallback(async () => {
    if (!applicationId.trim()) return;
    setBusy(true);
    try {
      await downloadApplicationBackupArchive(applicationId, author);
    } finally {
      setBusy(false);
    }
  }, [applicationId, author]);

  if (variant === "compact") {
    return (
      <Tooltip>
        <TooltipTrigger asChild>
          <Button
            type="button"
            size="icon"
            variant="outline"
            className={cn("h-8 w-8 shrink-0", className)}
            disabled={busy}
            onClick={() => void run()}
            aria-label="Tải bản sao lưu ZIP"
          >
            <Download className="h-4 w-4" />
          </Button>
        </TooltipTrigger>
        <TooltipContent side="left">Tải bản sao lưu đầy đủ (ZIP)</TooltipContent>
      </Tooltip>
    );
  }

  return (
    <Button
      type="button"
      variant="outline"
      size="sm"
      className={cn("gap-1.5", className)}
      disabled={busy}
      onClick={() => void run()}
    >
      <Download className="h-3.5 w-3.5" />
      {busy ? "Đang đóng gói…" : "Tải bản sao lưu"}
    </Button>
  );
}
