import { formatEvidenceMimeLabel, inferEvidenceFileKind } from "@/lib/evidenceFileKind";
import { EvidenceFileTypeIcon } from "./EvidenceFileTypeIcon";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Loader2, Trash2, Check, X, Upload, Eye } from "lucide-react";
import type { UseQueryResult } from "@tanstack/react-query";
import type { ApplicationItem } from "@/data/mockApplications";
import type { EvidenceBundle, EvidenceItemMeta, ServerEvidenceKind } from "@/lib/applicationEvidenceApi";
import { EVIDENCE_KIND_ROWS } from "./applicationEvidenceConstants";
import { hasEvidenceAccessUrl, inferKindFromMeta } from "./applicationEvidenceRowUtils";
import { formatIsoToDdMmYyyyHhMm } from "@/lib/vnDateFormat";

export type ApplicationEvidenceDashboardProps = {
  applicationId: string;
  applicationDetailQuery: UseQueryResult<ApplicationItem | null, Error>;
  bundle: EvidenceBundle;
  isStaff: boolean;
  canEditOwn: boolean;
  onOpenViewer: (kind: ServerEvidenceKind, meta: EvidenceItemMeta) => void;
  onUpload: (kind: ServerEvidenceKind, file: File) => void;
  onDelete: (kind: ServerEvidenceKind) => void;
  onReview: (kind: ServerEvidenceKind, decision: "approved" | "rejected") => void;
};

/**
 * Bảng minh chứng 2.1/2.2 (kho máy chủ) và thẻ tệp tham chiếu từ bản nộp (nếu có `applicationId`).
 */
export function ApplicationEvidenceDashboard({
  applicationId,
  applicationDetailQuery,
  bundle,
  isStaff,
  canEditOwn,
  onOpenViewer,
  onUpload,
  onDelete,
  onReview,
}: ApplicationEvidenceDashboardProps) {
  const showReference = Boolean(applicationId);

  return (
    <div className="h-full min-h-0 min-w-0 space-y-4 overflow-auto pr-1">
      {/* {showReference && applicationDetailQuery.isLoading ? (
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <Loader2 className="h-4 w-4 animate-spin" />
          Đang tải tham chiếu bản nộp…
        </div>
      ) : null}

      {showReference && applicationDetailQuery.data ? (
        <Card>
          <CardHeader className="py-3">
            <CardTitle className="text-base">Tệp kèm bản nộp (tham chiếu)</CardTitle>
            <CardDescription>
              Các liên kết từ hồ sơ đã gửi (toàn văn, tóm tắt, poster). Quản lý 2.1/2.2 ở bảng bên dưới.
            </CardDescription>
          </CardHeader>
          <CardContent className="flex flex-wrap gap-3 text-sm">
            {(["fullText", "abstract", "poster"] as const).map((k) => {
              const f = applicationDetailQuery.data?.files?.[k];
              if (!f?.url) return null;
              const kIcon = inferEvidenceFileKind(f);
              return (
                <a
                  key={k}
                  href={f.url}
                  target="_blank"
                  rel="noreferrer"
                  className="inline-flex items-center gap-2 rounded-md border px-2 py-1 hover:bg-muted"
                >
                  <EvidenceFileTypeIcon kind={kIcon} />
                  <span>{k === "fullText" ? "Toàn văn" : k === "abstract" ? "Tóm tắt" : "Poster"}</span>
                </a>
              );
            })}
            {!applicationDetailQuery.data?.files?.fullText &&
            !applicationDetailQuery.data?.files?.abstract &&
            !applicationDetailQuery.data?.files?.poster ? (
              <span className="text-muted-foreground">Không có tệp tham chiếu trong bản ghi này.</span>
            ) : null}
          </CardContent>
        </Card>
      ) : null} */}

      <div className="space-y-2 mt-4 px-2">
        <h2 className="text-sm font-medium text-foreground">Minh chứng kho máy chủ (2.1 / 2.2 / kỹ thuật)</h2>
        {!bundle.research && !bundle.textbook && !bundle.technical ? (
          <p className="text-xs text-amber-800 dark:text-amber-200/90 rounded-md border border-amber-500/30 bg-amber-50/60 px-3 py-2 dark:bg-amber-950/30">
            Phản hồi hiện tại: cả hai loại minh chứng đều chưa có trên kho. Dùng « Tải lên » ở từng dòng, hoặc tải từ workspace
            đăng ký (cùng mã case) khi hồ sơ vẫn cho phép sửa.
          </p>
        ) : null}
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[140px]">Loại</TableHead>
                <TableHead>Tên tệp / MIME</TableHead>
                <TableHead className="w-[100px]">Dung lượng</TableHead>
                <TableHead className="w-[120px]">Thẩm định</TableHead>
                <TableHead className="w-[200px] text-right">Thao tác</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {EVIDENCE_KIND_ROWS.map(({ key, title, desc }) => {
                const meta = bundle[key];
                const ik = meta ? inferKindFromMeta(meta) : "other";
                return (
                  <TableRow key={key}>
                    <TableCell className="align-top">
                      <div className="flex items-center gap-2 font-medium">
                        {meta ? <EvidenceFileTypeIcon kind={ik} className="h-4 w-4" /> : null}
                        <div>
                          <div>{title}</div>
                          <div className="text-xs font-normal text-muted-foreground">{desc}</div>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell className="align-top text-sm">
                      {meta ? (
                        formatEvidenceMimeLabel(meta.mimeType, meta.originalName)
                      ) : (
                        <span className="text-muted-foreground">—</span>
                      )}
                    </TableCell>
                    <TableCell className="align-top text-sm">
                      {meta?.byteSize != null ? (
                        <>{(meta.byteSize / 1024).toFixed(1)} KB</>
                      ) : (
                        <span className="text-muted-foreground">—</span>
                      )}
                    </TableCell>
                    <TableCell className="align-top text-sm">
                      {meta?.reviewStatus ? (
                        <span>
                          {meta.reviewStatus === "approved" ? "Đã duyệt" : "Từ chối"}
                          {meta.reviewedAt ? (
                            <span className="block text-xs text-muted-foreground">
                              {formatIsoToDdMmYyyyHhMm(meta.reviewedAt)}
                            </span>
                          ) : null}
                        </span>
                      ) : isStaff && meta ? (
                        <span className="text-muted-foreground">Chưa thẩm định</span>
                      ) : !meta ? (
                        <span className="text-muted-foreground">—</span>
                      ) : null}
                    </TableCell>
                    <TableCell className="text-right align-top">
                      <div className="inline-flex flex-wrap items-center justify-end gap-1.5">
                        {isStaff && meta ? (
                          <>
                            {hasEvidenceAccessUrl(meta) ? (
                              <Button
                                type="button"
                                size="sm"
                                variant="secondary"
                                className="gap-1"
                                onClick={() => onOpenViewer(key, meta)}
                              >
                                <Eye className="h-3.5 w-3.5" />
                              </Button>
                            ) : null}
                            <Button
                              type="button"
                              size="sm"
                              variant="default"
                              className="gap-1"
                              onClick={() => onReview(key, "approved")}
                            >
                              <Check className="h-3.5 w-3.5" />
                            </Button>
                            <Button
                              type="button"
                              size="sm"
                              variant="destructive"
                              className="gap-1"
                              onClick={() => onReview(key, "rejected")}
                            >
                              <X className="h-3.5 w-3.5" />
                            </Button>
                          </>
                        ) : null}
                        {canEditOwn ? (
                          <>
                            {meta && hasEvidenceAccessUrl(meta) ? (
                              <Button
                                type="button"
                                size="sm"
                                variant="link"
                                className="h-8 px-2"
                                onClick={() => onOpenViewer(key, meta)}
                              >
                                Xem / tải
                              </Button>
                            ) : null}
                            <label className="inline-flex cursor-pointer">
                              <input
                                type="file"
                                className="sr-only"
                                accept=".pdf,image/*,.doc,.docx,.xls,.xlsx,application/pdf,application/vnd.openxmlformats-officedocument.*"
                                onChange={(e) => {
                                  const f = e.target.files?.[0];
                                  e.target.value = "";
                                  if (f) void onUpload(key, f);
                                }}
                              />
                              <Button type="button" size="sm" variant="secondary" className="gap-1" asChild>
                                <span>
                                  <Upload className="h-3.5 w-3.5" />
                                  {meta ? "Thay tệp" : "Tải lên"}
                                </span>
                              </Button>
                            </label>
                            {meta ? (
                              <Button
                                type="button"
                                size="sm"
                                variant="outline"
                                className="gap-1"
                                onClick={() => onDelete(key)}
                              >
                                <Trash2 className="h-3.5 w-3.5" />
                                Xóa
                              </Button>
                            ) : null}
                          </>
                        ) : null}
                        {!isStaff && !canEditOwn && meta && hasEvidenceAccessUrl(meta) ? (
                          <Button type="button" size="sm" variant="link" onClick={() => onOpenViewer(key, meta)}>
                            Mở tệp
                          </Button>
                        ) : null}
                        {!isStaff && !canEditOwn && !meta ? <span className="text-xs text-muted-foreground">Chỉ xem</span> : null}
                      </div>
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </div>
      </div>
    </div>
  );
}
