import { useMemo, useState } from "react";
import { LayoutDashboard } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import type { ApplicationItem } from "@/data/mockApplications";
import { STATUS_OPTIONS, ALL_OPTION_VALUE } from "@/components/admin/SelectOptions";
import { ApplicantHistoryTable } from "@/components/applicant/history/ApplicantHistoryTable";
import type { EvidenceFileSlotKey } from "@/components/evidence/EvidenceFilesTableCell";

const APPLICANT_HISTORY_EVIDENCE_HIDE_KEYS: readonly EvidenceFileSlotKey[] = ["fullText"];

type SortBy = "submittedDate" | "name" | "status";
type SortOrder = "asc" | "desc";

interface ApplicantHistoryPanelProps {
  items: ApplicationItem[];
  loading: boolean;
  error: boolean;
  mutating?: boolean;
  selectedApplicationId?: string;
  /** Mở xem biểu mẫu đã nộp (chỉ đọc) */
  onOpenApplication?: (item: ApplicationItem) => void;
  /** Cùng nghĩa `onOpenApplication` (tương thích `ApplicationReviewPage`) */
  onViewApplication?: (item: ApplicationItem) => void;
  onCreateApplication?: () => void;
  /** Sửa biểu mẫu từ bản nháp Postgres (chuyển tới dashboard với mã case) */
  onUpdateApplicationForms?: (item: ApplicationItem) => void;
  /** Cùng nghĩa `onUpdateApplicationForms` */
  onEditApplicationForms?: (item: ApplicationItem) => void;
  /** Sửa tên hồ sơ / ngày nộp (hộp thoại) */
  onEditApplicationMetadata?: (item: ApplicationItem) => void;
  onDeleteApplication?: (applicationId: string) => Promise<unknown> | void;
}

export function ApplicantHistoryPanel({
  items,
  loading,
  error,
  mutating = false,
  selectedApplicationId,
  onOpenApplication,
  onViewApplication,
  onCreateApplication,
  onUpdateApplicationForms,
  onEditApplicationForms,
  onEditApplicationMetadata,
  onDeleteApplication,
}: ApplicantHistoryPanelProps) {
  const openApplication = onOpenApplication ?? onViewApplication;
  const updateApplicationForms = onUpdateApplicationForms ?? onEditApplicationForms;
  const [nameFilter, setNameFilter] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [yearFilter, setYearFilter] = useState<string>("");
  const [sortBy, setSortBy] = useState<SortBy>("submittedDate");
  const [sortOrder, setSortOrder] = useState<SortOrder>("desc");
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  const availableYears = useMemo(() => {
    const years = new Set<string>();
    for (const item of items) {
      const year = typeof item.calendarYear === "number"
        ? String(item.calendarYear)
        : String(new Date(item.submittedDate).getFullYear());
      if (year && year !== "NaN") years.add(year);
    }
    return Array.from(years).sort((a, b) => Number(b) - Number(a));
  }, [items]);

  const filteredAndSorted = useMemo(() => {
    const keyword = nameFilter.trim().toLowerCase();
    const rows = items.filter((item) => {
      if (keyword && !item.name.toLowerCase().includes(keyword)) return false;
      if (statusFilter && item.status !== statusFilter) return false;
      if (yearFilter) {
        const y = typeof item.calendarYear === "number"
          ? String(item.calendarYear)
          : String(new Date(item.submittedDate).getFullYear());
        if (y !== yearFilter) return false;
      }
      return true;
    });

    rows.sort((a, b) => {
      const order = sortOrder === "asc" ? 1 : -1;
      if (sortBy === "name") return a.name.localeCompare(b.name) * order;
      if (sortBy === "status") return String(a.status).localeCompare(String(b.status)) * order;
      return (new Date(a.submittedDate).getTime() - new Date(b.submittedDate).getTime()) * order;
    });

    return rows;
  }, [items, nameFilter, statusFilter, yearFilter, sortBy, sortOrder]);

  const totalItems = filteredAndSorted.length;
  const totalPages = Math.max(1, Math.ceil(totalItems / pageSize));
  const safePage = Math.min(page, totalPages);
  const pagedRows = filteredAndSorted.slice((safePage - 1) * pageSize, safePage * pageSize);

  const resetFilters = () => {
    setNameFilter("");
    setStatusFilter("");
    setYearFilter("");
    setSortBy("submittedDate");
    setSortOrder("desc");
    setPage(1);
  };

  const handleDelete = async (item: ApplicationItem) => {
    if (!onDeleteApplication) return;
    await onDeleteApplication(item.id);
  };

  const toggleSort = (nextSortBy: SortBy) => {
    if (sortBy === nextSortBy) {
      setSortOrder((prev) => (prev === "desc" ? "asc" : "desc"));
    } else {
      setSortBy(nextSortBy);
      setSortOrder("desc");
    }
    setPage(1);
  };

  return (
    <div className="mt-4 space-y-4">
      <Card>
        <CardHeader>
          <CardTitle>Lịch sử hồ sơ đã nộp của tôi</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
            <div className="space-y-2">
              <Label htmlFor="history-name">Tên sáng kiến</Label>
              <Input
                id="history-name"
                value={nameFilter}
                onChange={(e) => {
                  setNameFilter(e.target.value);
                  setPage(1);
                }}
                placeholder="Nhập tên sáng kiến"
              />
            </div>
            <div className="space-y-2">
              <Label>Trạng thái</Label>
              <Select
                value={statusFilter || ALL_OPTION_VALUE}
                onValueChange={(v) => {
                  setStatusFilter(v === ALL_OPTION_VALUE ? "" : v);
                  setPage(1);
                }}
              >
                <SelectTrigger><SelectValue placeholder="Chọn" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value={ALL_OPTION_VALUE}>Tất cả</SelectItem>
                  {STATUS_OPTIONS.map((option) => <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Năm nộp</Label>
              <Select
                value={yearFilter || ALL_OPTION_VALUE}
                onValueChange={(v) => {
                  setYearFilter(v === ALL_OPTION_VALUE ? "" : v);
                  setPage(1);
                }}
              >
                <SelectTrigger><SelectValue placeholder="Chọn năm" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value={ALL_OPTION_VALUE}>Tất cả</SelectItem>
                  {availableYears.map((year) => <SelectItem key={year} value={year}>{year}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="flex items-center gap-3">
            <Button onClick={() => setPage(1)}>Tìm</Button>
            <Button className="bg-black text-white" variant="ghost" onClick={resetFilters}>Xóa bộ lọc</Button>
            <Button
              type="button"
              className="gap-2"
              onClick={onCreateApplication}
            >
              <LayoutDashboard className="h-4 w-4" />
              Đăng ký mới
            </Button>
          </div>
        </CardContent>
      </Card>

      <ApplicantHistoryTable
        rows={pagedRows}
        loading={loading}
        error={error}
        mutating={mutating}
        selectedApplicationId={selectedApplicationId}
        sortBy={sortBy}
        onToggleSort={toggleSort}
        onOpenApplication={openApplication}
        onUpdateApplicationForms={updateApplicationForms}
        onEditApplicationMetadata={onEditApplicationMetadata}
        onDeleteApplication={onDeleteApplication ? handleDelete : undefined}
        evidenceHideFileKeys={APPLICANT_HISTORY_EVIDENCE_HIDE_KEYS}
      />

      <div className="flex flex-col justify-between gap-3 text-sm text-muted-foreground sm:flex-row sm:items-center">
        <div>Trang {safePage} / {totalPages} | Hiển thị {pageSize} / {totalItems} kết quả</div>
        <div className="flex items-center gap-2">
          <Select
            value={String(pageSize)}
            onValueChange={(v) => {
              setPageSize(Number(v));
              setPage(1);
            }}
          >
            <SelectTrigger className="w-[90px]"><SelectValue /></SelectTrigger>
            <SelectContent>
              {[10, 20, 50, 100].map((size) => <SelectItem key={size} value={String(size)}>{size}</SelectItem>)}
            </SelectContent>
          </Select>
          <Button variant="outline" size="sm" onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={safePage <= 1}>Trước</Button>
          <Button variant="outline" size="sm" onClick={() => setPage((p) => Math.min(totalPages, p + 1))} disabled={safePage >= totalPages}>Sau</Button>
        </div>
      </div>

    </div>
  );
}
