import { useState } from "react";
import { ArrowUpDown, Eye, Trash2, NotebookPen } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button, buttonVariants } from "@/components/ui/button";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { cn } from "@/lib/utils";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import type { ApplicationItem, ApplicationStatus } from "@/data/mockApplications";
import { EvidenceFilesTableCell, type EvidenceFileSlotKey } from "@/components/evidence/EvidenceFilesTableCell";
import { STATUS_OPTIONS } from "@/components/admin/SelectOptions";
import { formatIsoToDdMmYyyy, formatIsoToDdMmYyyyHhMm } from "@/lib/vnDateFormat";

type SortBy = "submittedDate" | "name" | "status";

function formatDate(iso: string | null | undefined, withTime = false) {
  if (!iso) return "";
  if (withTime) return formatIsoToDdMmYyyyHhMm(iso);
  return formatIsoToDdMmYyyy(iso);
}

function optionLabel(options: ReadonlyArray<{ value: string; label: string }>, value?: string | null) {
  if (value == null || value === "") return "";
  return options.find((o) => o.value === value)?.label ?? "";
}

function statusBadge(status: ApplicationStatus) {
  const label = optionLabel(STATUS_OPTIONS, status) || String(status);
  switch (status) {
    case "pending":
      return <Badge className="bg-amber-500 hover:bg-amber-500/90">{label}</Badge>;
    case "approved":
      return <Badge className="bg-green-600 hover:bg-green-600/90">{label}</Badge>;
    case "rejected":
      return <Badge variant="destructive">{label}</Badge>;
    case "transferred":
      return <Badge className="bg-blue-600 hover:bg-blue-600/90">{label}</Badge>;
    case "under_review":
      return <Badge variant="secondary">{label}</Badge>;
    case "reviewed":
      return <Badge variant="outline" className="border-green-500 text-green-700">{label}</Badge>;
    default:
      return <Badge variant="secondary">-</Badge>;
  }
}

function reviewStatusBadge(reviewStatus?: string) {
  switch (reviewStatus) {
    case "reviewed":
      return <Badge className="bg-green-600 hover:bg-green-600/90">Đã đánh giá</Badge>;
    case "under_review":
      return <Badge variant="secondary">Đang đánh giá</Badge>;
    case "not_reviewed":
      return <Badge variant="outline">Chưa đánh giá</Badge>;
    default:
      return <Badge variant="secondary">—</Badge>;
  }
}

interface ApplicantHistoryTableProps {
  rows: ApplicationItem[];
  loading: boolean;
  error: boolean;
  mutating?: boolean;
  selectedApplicationId?: string;
  sortBy: SortBy;
  onToggleSort: (sortBy: SortBy) => void;
  onOpenApplication?: (item: ApplicationItem) => void;
  /** Open dashboard with Postgres draft for this hồ sơ (sửa biểu mẫu) */
  onUpdateApplicationForms?: (item: ApplicationItem) => void;
  /** Tên hồ sơ / ngày nộp */
  onEditApplicationMetadata?: (item: ApplicationItem) => void;
  onDeleteApplication?: (item: ApplicationItem) => void;
  /** Cột minh chứng: ẩn liên kết tới một số loại tệp đã nộp (ví dụ toàn văn). */
  evidenceHideFileKeys?: ReadonlyArray<EvidenceFileSlotKey>;
}

export function ApplicantHistoryTable({
  rows,
  loading,
  error,
  mutating = false,
  selectedApplicationId,
  sortBy,
  onToggleSort,
  onOpenApplication,
  onUpdateApplicationForms,
  onEditApplicationMetadata,
  onDeleteApplication,
  evidenceHideFileKeys,
}: ApplicantHistoryTableProps) {
  const [deleteTarget, setDeleteTarget] = useState<ApplicationItem | null>(null);

  return (
    <div className="space-y-0">
    <div className="overflow-x-auto rounded-md border">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead className="w-[50px]">STT</TableHead>
            <TableHead className="w-[160px]">
              <button type="button" onClick={() => onToggleSort("submittedDate")} className="inline-flex items-center gap-1">
                Ngày gởi {sortBy === "submittedDate" ? <ArrowUpDown className="h-3 w-3" /> : null}
              </button>
            </TableHead>
            <TableHead className="min-w-[260px]">
              <button type="button" onClick={() => onToggleSort("name")} className="inline-flex items-center gap-1">
                Tên sáng kiến {sortBy === "name" ? <ArrowUpDown className="h-3 w-3" /> : null}
              </button>
            </TableHead>
            <TableHead className="w-[140px]">Trạng thái</TableHead>
            <TableHead className="w-[150px]">Trạng thái đánh giá</TableHead>
            <TableHead className="w-[60px] text-center">Minh chứng</TableHead>
            <TableHead className="w-[230px] text-center">Thao tác</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {loading ? (
            <TableRow>
              <TableCell colSpan={8} className="py-10 text-center text-muted-foreground">Đang tải dữ liệu...</TableCell>
            </TableRow>
          ) : error ? (
            <TableRow>
              <TableCell colSpan={8} className="py-10 text-center text-destructive">Không thể tải lịch sử hồ sơ.</TableCell>
            </TableRow>
          ) : rows.length === 0 ? (
            <TableRow>
              <TableCell colSpan={8} className="py-10 text-center text-muted-foreground">Không có hồ sơ phù hợp bộ lọc.</TableCell>
            </TableRow>
          ) : (
            rows.map((item, index) => (
              <TableRow key={item.id} data-state={selectedApplicationId === item.id ? "selected" : undefined}>
                <TableCell>{index + 1}</TableCell>
                <TableCell>{formatDate(item.submittedDate, true)}</TableCell>
                <TableCell className="max-w-[320px] truncate font-semibold" title={item.name}>{item.name}</TableCell>
                <TableCell>{statusBadge(item.status)}</TableCell>
                <TableCell>{reviewStatusBadge(item.reviewStatus)}</TableCell>
                <TableCell className="text-center">
                  <EvidenceFilesTableCell
                    item={item}
                    caseId={item.draftCaseId || item.draft_case_id}
                    hideFileKeys={evidenceHideFileKeys}
                  />
                </TableCell>
                <TableCell>
                  <div className="flex items-center justify-center gap-2">
                    <Button
                      size="icon"
                      variant="outline"
                      onClick={() => onOpenApplication?.(item)}
                      aria-label="Xem hồ sơ"
                      disabled={!onOpenApplication}
                    >
                      <Eye className="h-4 w-4" />
                    </Button>
                    <Button
                      size="icon"
                      variant="default"
                      onClick={() => onUpdateApplicationForms?.(item)}
                      aria-label="Cập nhật biểu mẫu từ dữ liệu đã lưu"
                      disabled={mutating || !onUpdateApplicationForms}
                      title="Cập nhật biểu mẫu (báo cáo, đơn, đóng góp)"
                    >
                      <NotebookPen className="h-4 w-4" />
                    </Button>
  
                    <Button
                      size="icon"
                      variant="destructive"
                      onClick={() => setDeleteTarget(item)}
                      aria-label="Xóa hồ sơ"
                      disabled={mutating || !onDeleteApplication}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))
          )}
        </TableBody>
      </Table>
    </div>

    <AlertDialog open={deleteTarget != null} onOpenChange={(open) => !open && setDeleteTarget(null)}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Xóa hồ sơ?</AlertDialogTitle>
          <AlertDialogDescription>
            {deleteTarget ? (
              <>
                Bạn có chắc muốn xóa hồ sơ <span className="font-medium text-foreground">"{deleteTarget.name}"</span>? Thao tác này không
                thể hoàn tác. Mã hồ sơ: <span className="font-mono text-xs text-foreground">{deleteTarget.id}</span>.
              </>
            ) : null}
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>Hủy</AlertDialogCancel>
          <AlertDialogAction
            className={cn(buttonVariants({ variant: "destructive" }))}
            onClick={() => {
              if (deleteTarget) void onDeleteApplication?.(deleteTarget);
            }}
          >
            Xóa hồ sơ
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
    </div>
  );
}
