import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import {
  Filter,
  RefreshCw,
  RotateCcw,
  Search,
  Trash2,
  X,
} from "lucide-react";
import { flattenCategoryOptions } from "../categories/categoryTree";
import { useCategoryTree as useRealCategoryTree } from "../categories/categoryState";
import { useDictionaries } from "../dictionaries/dictionaryContext";
import {
  deletedByLabel,
  formatLocalDate,
  toUtcIso,
} from "./recycleBinLabels";
import { useRecycleBinList } from "./recycleBinState";
import type {
  RecycleBinDocumentSummary,
  RecycleBinQuery,
} from "./recycleBinTypes";
import { RestoreDocumentModal } from "./RestoreDocumentModal";

const NAVY = "#1A5299";
const BLUE = "#3191eb";
const WHITE = "#fff";

export function RecycleBinModal({ onClose }: { onClose: () => void }) {
  const dictionaries = useDictionaries();
  const [keyword, setKeyword] = useState("");
  const [documentType, setDocumentType] = useState("");
  const [categoryId, setCategoryId] = useState("");
  const [deletedFromLocal, setDeletedFromLocal] = useState("");
  const [deletedToLocal, setDeletedToLocal] = useState("");
  const [sortField, setSortField] =
    useState<NonNullable<RecycleBinQuery["sortField"]>>("deletedAt");
  const [sortDirection, setSortDirection] =
    useState<NonNullable<RecycleBinQuery["sortDirection"]>>("desc");
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [restoring, setRestoring] =
    useState<RecycleBinDocumentSummary | null>(null);
  const [lastRestoredName, setLastRestoredName] = useState("");
  const categories = useRealCategoryTree();
  const flatCategories = flattenCategoryOptions(categories.tree);

  const query: RecycleBinQuery = {
    keyword: keyword.trim() || undefined,
    documentType: documentType
      ? (documentType as RecycleBinQuery["documentType"])
      : undefined,
    categoryId: categoryId || undefined,
    deletedFrom: toUtcIso(deletedFromLocal),
    deletedTo: toUtcIso(deletedToLocal),
    page,
    pageSize,
    sortField,
    sortDirection,
  };
  const list = useRecycleBinList(query);

  useEffect(() => {
    if (
      list.data &&
      list.data.totalPages > 0 &&
      page > list.data.totalPages
    ) {
      setPage(list.data.totalPages);
    }
  }, [list.data, page]);

  const resetPage = () => setPage(1);
  const clearFilters = () => {
    setKeyword("");
    setDocumentType("");
    setCategoryId("");
    setDeletedFromLocal("");
    setDeletedToLocal("");
    setSortField("deletedAt");
    setSortDirection("desc");
    setPage(1);
  };

  return createPortal(
    <div
      className="fixed inset-0 z-[100] flex items-center justify-center p-4 sm:p-6"
      style={{ background: "rgba(26,82,153,.55)" }}
      onClick={onClose}
    >
      <div
        className="w-[1500px] max-w-full h-[88vh] max-h-full flex flex-col bg-white shadow-2xl"
        onClick={(event) => event.stopPropagation()}
      >
        <div
          className="h-12 px-5 flex items-center text-white"
          style={{ background: NAVY }}
        >
          <Trash2 size={17} className="mr-2" />
          <span className="font-black">文档回收站</span>
          <button
            onClick={onClose}
            className="ml-auto flex items-center gap-1 text-sm font-black"
          >
            <X size={16} />
            返回后台管理
          </button>
        </div>

        <div
          className="p-3 grid grid-cols-12 gap-2 border-b"
          style={{ color: NAVY, borderColor: "rgba(40,118,193,.15)" }}
        >
          <label className="col-span-2 flex items-center h-9 border px-2">
            <Search size={13} className="mr-2" style={{ color: BLUE }} />
            <input
              value={keyword}
              onChange={(event) => {
                setKeyword(event.target.value);
                resetPage();
              }}
              placeholder="搜索文档或原文件名"
              className="min-w-0 flex-1 text-sm font-bold outline-none"
            />
          </label>
          <select
            value={documentType}
            onChange={(event) => {
              setDocumentType(event.target.value);
              resetPage();
            }}
            className="col-span-1 h-9 border px-2 text-xs font-bold"
          >
            <option value="">全部类型</option>
            {dictionaries.options("documentTypes").map((option) => (
              <option key={option.code} value={option.code}>
                {option.label}
              </option>
            ))}
          </select>
          <select
            value={categoryId}
            onChange={(event) => {
              setCategoryId(event.target.value);
              resetPage();
            }}
            className="col-span-2 h-9 border px-2 text-xs font-bold"
          >
            <option value="">全部分类</option>
            {flatCategories.map((category) => (
              <option key={category.id} value={category.id} title={category.categoryPath}>
                {category.displayLabel}
              </option>
            ))}
          </select>
          <input
            type="datetime-local"
            title="删除开始时间（含）"
            value={deletedFromLocal}
            onChange={(event) => {
              setDeletedFromLocal(event.target.value);
              resetPage();
            }}
            className="col-span-2 h-9 border px-2 text-xs font-bold"
          />
          <input
            type="datetime-local"
            title="删除结束时间（不含）"
            value={deletedToLocal}
            onChange={(event) => {
              setDeletedToLocal(event.target.value);
              resetPage();
            }}
            className="col-span-2 h-9 border px-2 text-xs font-bold"
          />
          <select
            value={sortField}
            onChange={(event) => {
              setSortField(event.target.value as typeof sortField);
              resetPage();
            }}
            className="col-span-1 h-9 border px-2 text-xs font-bold"
          >
            <option value="deletedAt">删除时间</option>
            <option value="documentName">文档名称</option>
            <option value="documentType">文档类型</option>
            <option value="updatedAt">更新时间</option>
          </select>
          <select
            value={sortDirection}
            onChange={(event) => {
              setSortDirection(event.target.value as "asc" | "desc");
              resetPage();
            }}
            className="col-span-1 h-9 border px-2 text-xs font-bold"
          >
            <option value="desc">降序</option>
            <option value="asc">升序</option>
          </select>
          <div className="col-span-1 flex gap-1">
            <button
              title="清空筛选"
              onClick={clearFilters}
              className="flex-1 h-9 border"
              style={{ borderColor: BLUE }}
            >
              <Filter size={13} className="mx-auto" />
            </button>
            <button
              title="刷新"
              onClick={list.refresh}
              className="flex-1 h-9 text-white"
              style={{ background: BLUE }}
            >
              <RefreshCw size={13} className="mx-auto" />
            </button>
          </div>
        </div>

        {lastRestoredName && (
          <div
            className="px-4 py-2 text-xs font-bold"
            style={{ color: NAVY, background: "#EBF4FD" }}
          >
            已恢复：{lastRestoredName}。后台统计、分类、文档与附件数据已请求刷新。
          </div>
        )}

        <div className="flex-1 overflow-auto">
          {list.loading && !list.data && (
            <div className="p-12 text-center font-bold" style={{ color: NAVY }}>
              <RefreshCw size={15} className="inline animate-spin mr-2" />
              正在加载回收站…
            </div>
          )}
          {list.error && (
            <div className="p-12 text-center font-bold" style={{ color: NAVY }}>
              <div>
                {list.error.httpStatus === 403
                  ? "当前账号无权访问回收站"
                  : list.error.message}
              </div>
              {list.error.requestId && (
                <div className="text-xs opacity-60 mt-1">
                  错误编号：{list.error.requestId}
                </div>
              )}
              <button
                onClick={list.refresh}
                className="mt-3 px-4 py-2 text-sm text-white"
                style={{ background: BLUE }}
              >
                重试
              </button>
            </div>
          )}
          {list.data?.items.length === 0 && (
            <div className="p-12 text-center font-bold opacity-60" style={{ color: NAVY }}>
              回收站暂无符合条件的文档
            </div>
          )}
          {list.data && list.data.items.length > 0 && (
            <table className="w-full min-w-[1280px] border-collapse">
              <thead className="sticky top-0 z-10 text-white" style={{ background: NAVY }}>
                <tr>
                  {[
                    "序号",
                    "文档名称",
                    "类型",
                    "原文件名",
                    "分类",
                    "父主案ID",
                    "密级",
                    "状态",
                    "删除时间",
                    "删除人",
                    "操作",
                  ].map((heading) => (
                    <th key={heading} className="px-3 py-3 text-left text-xs font-black">
                      {heading}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {list.data.items.map((item, index) => (
                  <tr
                    key={item.id}
                    className="border-b"
                    style={{
                      color: NAVY,
                      borderColor: "rgba(40,118,193,.1)",
                      background: index % 2 ? "rgba(40,118,193,.04)" : WHITE,
                    }}
                  >
                    <td className="px-3 py-2 text-xs font-black">
                      {(list.data!.page - 1) * list.data!.pageSize + index + 1}
                    </td>
                    <td className="px-3 py-2 text-sm font-black">
                      {item.documentName}
                    </td>
                    <td className="px-3 py-2 text-xs font-bold">
                      {dictionaries.label("documentTypes", item.documentType)}
                    </td>
                    <td className="px-3 py-2 text-xs font-bold max-w-[220px] truncate">
                      {item.originalFileName}
                    </td>
                    <td className="px-3 py-2 text-xs font-bold">
                      {item.categoryName ?? "—"}
                    </td>
                    <td className="px-3 py-2 text-xs font-mono">
                      {item.parentDocumentId ?? "—"}
                    </td>
                    <td className="px-3 py-2 text-xs font-bold">
                      {dictionaries.label("securityLevels", item.securityLevel)}
                    </td>
                    <td className="px-3 py-2 text-xs font-bold">
                      {dictionaries.label("documentStatuses", item.documentStatus)}
                    </td>
                    <td className="px-3 py-2 text-xs font-bold whitespace-nowrap">
                      {formatLocalDate(item.deletedAt)}
                    </td>
                    <td className="px-3 py-2 text-xs font-bold">
                      {deletedByLabel(item.deletedBy)}
                    </td>
                    <td className="px-3 py-2">
                      <button
                        onClick={() => setRestoring(item)}
                        className="px-3 py-1.5 text-xs font-black text-white"
                        style={{ background: BLUE }}
                      >
                        <RotateCcw size={12} className="inline mr-1" />
                        恢复
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        <div
          className="h-12 px-4 flex items-center justify-center gap-3 border-t text-xs font-bold"
          style={{ color: NAVY, borderColor: "rgba(40,118,193,.15)" }}
        >
          <span>共 {list.data?.total ?? 0} 条</span>
          <select
            value={pageSize}
            onChange={(event) => {
              setPageSize(Number(event.target.value));
              setPage(1);
            }}
            className="h-8 border px-2"
          >
            {[20, 50, 100].map((size) => (
              <option key={size} value={size}>
                每页 {size}
              </option>
            ))}
          </select>
          <button
            disabled={page <= 1}
            onClick={() => setPage((value) => Math.max(1, value - 1))}
            className="px-3 py-1 border disabled:opacity-30"
          >
            上一页
          </button>
          <span>
            第 {list.data?.page ?? page} / {list.data?.totalPages ?? 0} 页
          </span>
          <button
            disabled={!list.data || page >= list.data.totalPages}
            onClick={() => setPage((value) => value + 1)}
            className="px-3 py-1 border disabled:opacity-30"
          >
            下一页
          </button>
        </div>
      </div>

      {restoring && (
        <RestoreDocumentModal
          item={restoring}
          onClose={() => setRestoring(null)}
          onConflict={list.refresh}
          onRestored={(result) => {
            setLastRestoredName(result.document.documentName);
            list.refresh();
          }}
        />
      )}
    </div>,
    document.body,
  );
}
