import { EvidenceVaultLinkButton } from "@/components/evidence/EvidenceVaultLinkButton";
import type { ApplicationFile, ApplicationItem } from "@/data/mockApplications";
import { inferEvidenceFileKind } from "@/lib/evidenceFileKind";
import { resolveApplicationAssetUrl } from "@/lib/resolveApplicationAssetUrl";
import { EvidenceFileTypeIcon } from "./EvidenceFileTypeIcon";

const FILE_KEYS = ["fullText", "abstract", "poster"] as const;
export type EvidenceFileSlotKey = (typeof FILE_KEYS)[number];

function fileEntry(
  key: EvidenceFileSlotKey,
  f: ApplicationFile | null | undefined,
): { key: string; file: ApplicationFile; label: string } | null {
  const href = (f?.viewUrl ?? f?.url ?? "").trim();
  if (!href) return null;
  return {
    key,
    file: f,
    label: key === "fullText" ? "Toàn văn" : key === "abstract" ? "Tóm tắt" : "Poster",
  };
}

export interface EvidenceFilesTableCellProps {
  item: ApplicationItem;
  /** Mã `case_code` (Postgres) — cần để mở kho minh chứng 2.1/2.2. */
  caseId: string | undefined;
  /** Do not show links for these submitted file slots (e.g. `fullText` in applicant history). */
  hideFileKeys?: ReadonlyArray<EvidenceFileSlotKey>;
}

/**
 * Ô bảng: tất cả minh chứng từ hồ sơ (@link, pdf, hình, docx, excel) + nút mở kho xem/duyệt.
 */
export function EvidenceFilesTableCell({ item, caseId, hideFileKeys }: EvidenceFilesTableCellProps) {
  const keys: EvidenceFileSlotKey[] = hideFileKeys?.length
    ? FILE_KEYS.filter((k) => !hideFileKeys.includes(k))
    : [...FILE_KEYS];
  const entries = keys.map((k) => fileEntry(k, item.files?.[k])).filter(Boolean) as {
    key: string;
    file: ApplicationFile;
    label: string;
  }[];

  const showVault = Boolean(caseId?.trim() && item.id);

  if (entries.length === 0 && !showVault) {
    return <span className="text-muted-foreground text-xs">—</span>;
  }

  return (
    <div className="flex flex-wrap items-center justify-center gap-1.5">
      {entries.map((e) => {
        const k = inferEvidenceFileKind(e.file);
        return (
          <a
            key={e.key}
            href={resolveApplicationAssetUrl(e.file.viewUrl || e.file.url)}
            target="_blank"
            rel="noreferrer"
            className="inline-flex rounded-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
            title={`${e.label} — mở tệp đã nộp`}
            aria-label={`Mở ${e.label} (${e.file.type || k})`}
          >
            <EvidenceFileTypeIcon kind={k} title={e.label} />
          </a>
        );
      })}
      {showVault ? <EvidenceVaultLinkButton caseId={caseId!} applicationId={item.id} /> : null}
    </div>
  );
}
