"use client";

import { useCallback } from "react";
import { Network } from "lucide-react";
import { BrapiEntityPage } from "@/components/brapi/BrapiEntityPage";
import {
  createOntologyRow,
  deleteOntologyRow,
  fetchOntologyDetail,
  fetchOntologyRows,
  updateOntologyRow,
} from "./api";

const ontologyFields = [
  { key: "ontologyName", label: "本体名称 (Ontology Name)", type: "text" as const, required: true, placeholder: "如 Crop Ontology - Maize" },
  { key: "version", label: "版本号", type: "text" as const, placeholder: "3.2.0" },
  { key: "authors", label: "作者", type: "text" as const, placeholder: "维护组织或作者" },
  { key: "licence", label: "许可", type: "text" as const, placeholder: "如 CC BY 4.0" },
  { key: "copyright", label: "版权", type: "text" as const },
  { key: "documentationURL", label: "文档地址", type: "text" as const, placeholder: "https://cropontology.org/ontology/CO_322", colSpan: 2 as const },
  { key: "description", label: "说明", type: "textarea" as const, placeholder: "本体用途、作物范围或维护说明", colSpan: 2 as const },
];

export default function OntologyDictionaryPage() {
  const loadOntologyRows = useCallback(async () => {
    const rows = await fetchOntologyRows();
    return rows as unknown as Record<string, unknown>[];
  }, []);

  const loadOntologyRecord = useCallback(async (ontologyDbId: string) => {
    const row = await fetchOntologyDetail(ontologyDbId);
    return row as unknown as Record<string, unknown>;
  }, []);

  const createOntologyRecord = useCallback(async (payload: Record<string, unknown>) => {
    const row = await createOntologyRow(payload);
    return row as unknown as Record<string, unknown>;
  }, []);

  const updateOntologyRecord = useCallback(async (id: string, payload: Record<string, unknown>) => {
    const row = await updateOntologyRow(id, payload);
    return row as unknown as Record<string, unknown>;
  }, []);

  return (
    <BrapiEntityPage
      icon={Network}
      iconBg="bg-gradient-to-br from-amber-600 to-orange-700"
      title="Ontology 本体"
      description="维护 Crop Ontology 或企业内部性状本体，作为 Trait / Method / Scale 的来源标准"
      addLabel="新增本体"
      columns={[
        { key: "ontologyDbId", label: "Ontology DbId" },
        { key: "ontologyName", label: "本体名称" },
        { key: "version", label: "版本" },
        { key: "documentationURL", label: "文档地址" },
        { key: "authors", label: "作者" },
        { key: "licence", label: "许可" },
      ]}
      fields={ontologyFields}
      data={[]}
      stats={[{ label: "/brapi/v2/ontologies", value: "BrAPI", className: "bg-amber-50 text-amber-700 dark:bg-amber-400/10 dark:text-amber-200" }]}
      loadData={loadOntologyRows}
      fetchRecord={loadOntologyRecord}
      createRecord={createOntologyRecord}
      updateRecord={updateOntologyRecord}
      deleteRecord={deleteOntologyRow}
    />
  );
}
