"use client";

import Link from "next/link";
import { useCallback, useMemo, useState } from "react";
import { List } from "lucide-react";
import { BrapiEntityPage } from "@/components/brapi/BrapiEntityPage";
import { Button } from "@/components/ui/button";
import {
  createListRow,
  fetchListDetail,
  fetchListRows,
  fetchPersonOptions,
  updateListRow,
} from "./api";
import { buildListFormFields } from "./components/listFormFields";
import { listTypeLabel, type SelectOption } from "./types";

export default function ListDictionaryPage() {
  const [personOptions, setPersonOptions] = useState<SelectOption[]>([]);

  const loadRows = useCallback(async () => {
    const [people, rows] = await Promise.all([fetchPersonOptions(), fetchListRows()]);
    setPersonOptions(people);
    return rows as unknown as Record<string, unknown>[];
  }, []);

  const fields = useMemo(() => buildListFormFields(personOptions), [personOptions]);

  const createRecord = useCallback(
    async (payload: Record<string, unknown>) => createListRow(payload) as unknown as Record<string, unknown>,
    [],
  );

  const updateRecord = useCallback(
    async (id: string, payload: Record<string, unknown>) => updateListRow(id, payload) as unknown as Record<string, unknown>,
    [],
  );

  const fetchRecord = useCallback(
    async (id: string) => fetchListDetail(id) as unknown as Record<string, unknown>,
    [],
  );

  return (
    <BrapiEntityPage
      icon={List}
      iconBg="bg-gradient-to-br from-violet-500 to-purple-600"
      title="List 通用列表"
      description="维护 BrAPI 通用分组列表，可在详情页管理 list_item 明细"
      addLabel="新增列表"
      useEnhancedDialog
      columns={[
        { key: "listName", label: "列表名称" },
        {
          key: "listType",
          label: "类型",
          render: (value) => listTypeLabel(value),
        },
        { key: "listSize", label: "项数" },
        { key: "listOwnerName", label: "Owner" },
        { key: "listSource", label: "来源" },
        {
          key: "id",
          label: "明细",
          render: (_value, row) => {
            const id = String(row.id ?? row.listDbId ?? "");
            if (!id) return <span className="text-slate-300">—</span>;
            return (
              <Button variant="link" className="h-auto p-0 text-violet-600 dark:text-violet-300" asChild>
                <Link href={`/basic-dictionary/base/list/${encodeURIComponent(id)}`}>管理明细</Link>
              </Button>
            );
          },
        },
      ]}
      fields={fields}
      data={[]}
      stats={[{ label: "/brapi/v2/lists", value: "BrAPI", className: "bg-violet-50 text-violet-700 dark:bg-violet-400/10 dark:text-violet-200" }]}
      loadData={loadRows}
      fetchRecord={fetchRecord}
      createRecord={createRecord}
      updateRecord={updateRecord}
    />
  );
}
