import { Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { FolderArchive, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { getApplicationEvidence } from "@/lib/applicationEvidenceApi";
import { cn } from "@/lib/utils";
import { deriveEvidenceVaultAggregateLabel } from "@/components/evidence/applicationEvidenceRowUtils";

export type EvidenceVaultLinkButtonProps = {
  caseId: string;
  applicationId: string;
  className?: string;
};

/**
 * Mở kho minh chứng 2.1 / 2.2 / kỹ thuật (`/dashboard/documents/:caseId/evidence`).
 * Nhãn màu theo kết quả phê duyệt giống bảng {@link ApplicationEvidenceDashboard} (Đạt / Không đạt / Chưa xem).
 */
export function EvidenceVaultLinkButton({ caseId, applicationId, className }: EvidenceVaultLinkButtonProps) {
  const c = caseId.trim();
  const a = applicationId.trim();
  if (!c || !a) return null;

  const evidenceQuery = useQuery({
    queryKey: ["evidence", c],
    queryFn: () => getApplicationEvidence(c),
    enabled: true,
    retry: (failureCount, err) => {
      const st = (err as { status?: number })?.status;
      if (st === 401 || st === 403 || st === 503) return false;
      return failureCount < 2;
    },
  });

  const href = `/dashboard/documents/${encodeURIComponent(c)}/evidence?applicationId=${encodeURIComponent(a)}`;

  const bundle = evidenceQuery.data;
  const showSpinner = bundle == null && evidenceQuery.isFetching;
  const loadError = evidenceQuery.isError;
  const { label, textClassName } =
    bundle != null
      ? deriveEvidenceVaultAggregateLabel(bundle)
      : { label: "Chưa xem" as const, textClassName: "text-foreground" };

  return (
    <Button variant="outline" size="sm" className={className} asChild>
      <Link
        to={href}
        title={`Mở kho minh chứng — ${label}`}
        aria-busy={showSpinner}
      >
        <FolderArchive className="h-4 w-4 shrink-0" aria-hidden />
        {showSpinner ? (
          <Loader2 className="ml-1.5 h-3.5 w-3.5 animate-spin shrink-0 text-muted-foreground" aria-hidden />
        ) : loadError ? (
          <span className="ml-1.5 text-xs text-destructive font-medium" title="Không tải được trạng thái minh chứng">
            Lỗi tải
          </span>
        ) : (
          <span className={cn("ml-1.5 font-medium", textClassName)}>{label}</span>
        )}
      </Link>
    </Button>
  );
}
