import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
  getJSON,
  getJSONAuth,
  itemsOrEmpty,
  type AdminResource,
  type Category,
} from "../../../api";
import { getToken } from "../../../admin/token";
import { resourceTypeDisplay } from "../../../resourceTypeLabels";
import { useAdminT } from "../../../admin/useAdminT";
import { adminUiPrefix } from "../../../adminPaths";
import { useAdminRouterMode } from "../../../adminRouterMode";

function statusLabel(t: (k: string) => string, s: string) {
  if (s === "published") return t("published");
  if (s === "draft") return t("draft");
  if (s === "archived") return t("archived");
  return s;
}

const pageSize = 25;

export function AdminResources() {
  const t = useAdminT();
  const mode = useAdminRouterMode();
  const token = getToken();
  const [items, setItems] = useState<AdminResource[]>([]);
  const [catNames, setCatNames] = useState<Record<number, string>>({});
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);

  useEffect(() => {
    getJSON<Category[]>("/api/categories?lang=zh-CN")
      .then((cats) => {
        const m: Record<number, string> = {};
        for (const c of cats) m[c.id] = c.name;
        setCatNames(m);
      })
      .catch(() => setCatNames({}));
  }, []);

  useEffect(() => {
    getJSONAuth<{ items: AdminResource[]; total?: number }>(
      `/api/admin/resources?limit=${pageSize}&page=${page}`,
      token,
    )
      .then((r) => {
        setItems(itemsOrEmpty(r.items));
        setTotal(typeof r.total === "number" ? r.total : 0);
      })
      .catch(() => setItems([]));
  }, [token, page]);

  const pages = Math.max(1, Math.ceil(total / pageSize));

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between gap-3">
        <h1 className="text-2xl font-bold">{t("resources")}</h1>
        <Link
          to={mode === "basename" ? "new" : `${adminUiPrefix}/resources/new`}
          className="rounded-xl bg-ark-gold px-4 py-2 text-sm font-semibold text-black"
        >
          {t("newResource")}
        </Link>
      </div>
      <p className="text-sm text-neutral-500">
        {t("listRange")
          .replace(
            "{{from}}",
            String(total === 0 ? 0 : (page - 1) * pageSize + 1),
          )
          .replace("{{to}}", String(Math.min(page * pageSize, total)))
          .replace("{{total}}", String(total))}
      </p>
      <div className="flex flex-wrap gap-2">
        <button
          type="button"
          disabled={page <= 1}
          onClick={() => setPage((p) => Math.max(1, p - 1))}
          className="rounded-full border border-ark-line px-4 py-2 text-sm text-neutral-200 outline-none hover:border-ark-gold disabled:opacity-40"
        >
          {t("paginationPrev")}
        </button>
        <span className="flex items-center px-2 text-sm text-ark-muted tabular-nums">
          {t("pageIndicator")
            .replace("{{c}}", String(page))
            .replace("{{p}}", String(pages))}
        </span>
        <button
          type="button"
          disabled={page >= pages}
          onClick={() => setPage((p) => Math.min(pages, p + 1))}
          className="rounded-full border border-ark-line px-4 py-2 text-sm text-neutral-200 outline-none hover:border-ark-gold disabled:opacity-40"
        >
          {t("paginationNext")}
        </button>
      </div>
      <div className="overflow-x-auto rounded-2xl border border-ark-line">
        <table className="w-full text-sm">
          <thead className="bg-ark-panel text-left text-neutral-400">
            <tr>
              <th className="p-3">{t("title")}</th>
              <th className="p-3">{t("category")}</th>
              <th className="p-3">{t("type")}</th>
              <th className="p-3">{t("status")}</th>
              <th className="p-3">{t("downloads")}</th>
              <th className="p-3" />
            </tr>
          </thead>
          <tbody>
            {items.map((r) => (
              <tr key={r.id} className="border-t border-ark-line">
                <td className="p-3 font-medium">{r.title}</td>
                <td className="p-3 text-neutral-400">
                  {catNames[r.categoryId] ?? r.categoryId}
                </td>
                <td className="p-3 text-neutral-400">
                  {resourceTypeDisplay(t, r.type)}
                </td>
                <td className="p-3 text-neutral-400">
                  {statusLabel(t, r.status)}
                </td>
                <td className="p-3 text-neutral-400">{r.downloadCount ?? 0}</td>
                <td className="p-3 text-right">
                  <Link
                    className="text-ark-gold2 hover:underline"
                    to={
                      mode === "basename"
                        ? String(r.id)
                        : `${adminUiPrefix}/resources/${r.id}`
                    }
                  >
                    {t("edit")}
                  </Link>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
