"use client";

import { useCallback, useMemo, useState } from "react";
import { Activity, Ruler, Sigma } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField, type BrapiTableColumn } from "@/components/brapi/BrapiEntityPage";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  createTraitMethodScaleRow,
  deleteTraitMethodScaleRow,
  fetchOntologyOptions,
  fetchTraitMethodScaleRows,
  updateTraitMethodScaleRow,
} from "./api";
import { NONE_ONTOLOGY_VALUE, type OntologyOption, type TraitMethodScaleKind } from "./types";

const kindTabs: Array<{ value: TraitMethodScaleKind; label: string }> = [
  { value: "Trait", label: "Trait 性状" },
  { value: "Method", label: "Method 方法" },
  { value: "Scale", label: "Scale 标尺" },
];

const ontologyField = (ontologyOptions: OntologyOption[]): BrapiFormField => ({
  key: "ontology_id",
  label: "所属 Ontology",
  type: "select",
  options: [{ value: NONE_ONTOLOGY_VALUE, label: "不关联本体" }, ...ontologyOptions],
});

const commonFields = (ontologyOptions: OntologyOption[]): BrapiFormField[] => [
  { key: "name", label: "名称", type: "text", required: true },
  ontologyField(ontologyOptions),
  { key: "pui", label: "PUI", type: "text", placeholder: "永久唯一标识" },
];

const columnsByKind: Record<TraitMethodScaleKind, BrapiTableColumn[]> = {
  Trait: [
    { key: "db_id", label: "Trait ID" },
    { key: "name", label: "性状名称" },
    { key: "class", label: "性状分类" },
    { key: "ontology_name", label: "Ontology" },
    { key: "pui", label: "PUI" },
    { key: "description", label: "性状描述" },
  ],
  Method: [
    { key: "db_id", label: "Method ID" },
    { key: "name", label: "方法名称" },
    { key: "class", label: "方法分类" },
    { key: "ontology_name", label: "Ontology" },
    { key: "formula", label: "公式" },
    { key: "reference", label: "参考资料" },
    { key: "description", label: "方法说明" },
  ],
  Scale: [
    { key: "db_id", label: "Scale ID" },
    { key: "name", label: "标尺名称" },
    { key: "ontology_name", label: "Ontology" },
    { key: "units", label: "单位" },
    { key: "data_type", label: "数据类型" },
    { key: "decimal_places", label: "小数位" },
    { key: "valid_value_min", label: "最小值" },
    { key: "valid_value_max", label: "最大值" },
    { key: "pui", label: "PUI" },
  ],
};

const statsByKind = {
  Trait: [{ label: "/brapi/v2/traits", value: "Trait", className: "bg-green-50 text-green-700 dark:bg-green-400/10 dark:text-green-200" }],
  Method: [{ label: "/brapi/v2/methods", value: "Method", className: "bg-blue-50 text-blue-700 dark:bg-blue-400/10 dark:text-blue-200" }],
  Scale: [{ label: "/brapi/v2/scales", value: "Scale", className: "bg-amber-50 text-amber-700 dark:bg-amber-400/10 dark:text-amber-200" }],
};

function useOntologyOptions() {
  const [ontologyOptions, setOntologyOptions] = useState<OntologyOption[]>([]);

  const ensureOntologyOptions = useCallback(async () => {
    const options = await fetchOntologyOptions();
    setOntologyOptions(options);
    return options;
  }, []);

  return { ontologyOptions, ensureOntologyOptions };
}

function TraitTab({ ontologyOptions, ensureOntologyOptions }: { ontologyOptions: OntologyOption[]; ensureOntologyOptions: () => Promise<OntologyOption[]> }) {
  const loadRows = useCallback(async () => {
    await ensureOntologyOptions();
    return fetchTraitMethodScaleRows("Trait") as unknown as Promise<Record<string, unknown>[]>;
  }, [ensureOntologyOptions]);

  const fields = useMemo<BrapiFormField[]>(() => [
    ...commonFields(ontologyOptions),
    { key: "class", label: "性状分类", type: "text", placeholder: "如 morphological、yield、quality" },
    { key: "description", label: "性状描述", type: "textarea", placeholder: "描述这个性状测量的生物学含义", colSpan: 2 },
  ], [ontologyOptions]);

  return (
    <BrapiEntityPage
      icon={Activity}
      iconBg="bg-gradient-to-br from-green-500 to-emerald-600"
      title="Trait 性状"
      description="维护测什么，例如株高、产量、蛋白含量等性状定义"
      addLabel="新增性状"
      columns={columnsByKind.Trait}
      fields={fields}
      data={[]}
      stats={statsByKind.Trait}
      loadData={loadRows}
      createRecord={(payload) => createTraitMethodScaleRow({ ...payload, kind: "Trait" }) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updateTraitMethodScaleRow(id, { ...payload, kind: "Trait" }) as unknown as Promise<Record<string, unknown>>}
      deleteRecord={deleteTraitMethodScaleRow}
    />
  );
}

function MethodTab({ ontologyOptions, ensureOntologyOptions }: { ontologyOptions: OntologyOption[]; ensureOntologyOptions: () => Promise<OntologyOption[]> }) {
  const loadRows = useCallback(async () => {
    await ensureOntologyOptions();
    return fetchTraitMethodScaleRows("Method") as unknown as Promise<Record<string, unknown>[]>;
  }, [ensureOntologyOptions]);

  const fields = useMemo<BrapiFormField[]>(() => [
    ...commonFields(ontologyOptions),
    { key: "class", label: "方法分类", type: "text", placeholder: "如 measurement、calculation、visual scoring" },
    { key: "formula", label: "公式", type: "text", placeholder: "如 fresh_weight / plot_area" },
    { key: "reference", label: "参考资料", type: "text", placeholder: "方法来源、标准或论文" },
    { key: "description", label: "方法说明", type: "textarea", placeholder: "说明具体怎么测、采样位置、采样时机等", colSpan: 2 },
  ], [ontologyOptions]);

  return (
    <BrapiEntityPage
      icon={Sigma}
      iconBg="bg-gradient-to-br from-blue-500 to-cyan-600"
      title="Method 方法"
      description="维护怎么测，例如直尺测量、公式计算、人工分级等方法"
      addLabel="新增方法"
      columns={columnsByKind.Method}
      fields={fields}
      data={[]}
      stats={statsByKind.Method}
      loadData={loadRows}
      createRecord={(payload) => createTraitMethodScaleRow({ ...payload, kind: "Method" }) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updateTraitMethodScaleRow(id, { ...payload, kind: "Method" }) as unknown as Promise<Record<string, unknown>>}
      deleteRecord={deleteTraitMethodScaleRow}
    />
  );
}

function ScaleTab({ ontologyOptions, ensureOntologyOptions }: { ontologyOptions: OntologyOption[]; ensureOntologyOptions: () => Promise<OntologyOption[]> }) {
  const loadRows = useCallback(async () => {
    await ensureOntologyOptions();
    return fetchTraitMethodScaleRows("Scale") as unknown as Promise<Record<string, unknown>[]>;
  }, [ensureOntologyOptions]);

  const fields = useMemo<BrapiFormField[]>(() => [
    ...commonFields(ontologyOptions),
    { key: "units", label: "单位", type: "text", placeholder: "如 cm、kg、%" },
    { key: "data_type", label: "数据类型", type: "number", placeholder: "可选数字枚举" },
    { key: "decimal_places", label: "小数位", type: "number", placeholder: "如 0、1、2" },
    { key: "valid_value_min", label: "最小值", type: "text" },
    { key: "valid_value_max", label: "最大值", type: "text" },
  ], [ontologyOptions]);

  return (
    <BrapiEntityPage
      icon={Ruler}
      iconBg="bg-gradient-to-br from-orange-500 to-amber-600"
      title="Scale 标尺"
      description="维护用什么单位和取值范围，例如厘米、公斤、百分比或等级"
      addLabel="新增标尺"
      columns={columnsByKind.Scale}
      fields={fields}
      data={[]}
      stats={statsByKind.Scale}
      loadData={loadRows}
      createRecord={(payload) => createTraitMethodScaleRow({ ...payload, kind: "Scale" }) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updateTraitMethodScaleRow(id, { ...payload, kind: "Scale" }) as unknown as Promise<Record<string, unknown>>}
      deleteRecord={deleteTraitMethodScaleRow}
    />
  );
}

export default function TraitMethodScalePage() {
  const { ontologyOptions, ensureOntologyOptions } = useOntologyOptions();

  return (
    <Tabs defaultValue="Trait" className="flex min-h-full flex-col gap-4">
      <TabsList className="w-full justify-start overflow-x-auto rounded-lg border bg-white p-1 dark:border-slate-800 dark:bg-slate-950 sm:w-fit">
        {kindTabs.map((tab) => (
          <TabsTrigger key={tab.value} value={tab.value}>
            {tab.label}
          </TabsTrigger>
        ))}
      </TabsList>

      <TabsContent value="Trait" className="mt-0 min-h-0 flex-1">
        <TraitTab ontologyOptions={ontologyOptions} ensureOntologyOptions={ensureOntologyOptions} />
      </TabsContent>
      <TabsContent value="Method" className="mt-0 min-h-0 flex-1">
        <MethodTab ontologyOptions={ontologyOptions} ensureOntologyOptions={ensureOntologyOptions} />
      </TabsContent>
      <TabsContent value="Scale" className="mt-0 min-h-0 flex-1">
        <ScaleTab ontologyOptions={ontologyOptions} ensureOntologyOptions={ensureOntologyOptions} />
      </TabsContent>
    </Tabs>
  );
}
