"use client";

import { useCallback, useMemo, useState } from "react";
import { ClipboardList } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField } from "@/components/brapi/BrapiEntityPage";
import {
  createObservationVariableRow,
  deleteObservationVariableRow,
  fetchObservationVariableOptions,
  fetchObservationVariableRows,
  updateObservationVariableRow,
} from "./api";
import { NONE_SELECT_VALUE, type SelectOption } from "./types";

const statusOptions: SelectOption[] = [
  { value: NONE_SELECT_VALUE, label: "不指定状态" },
  { value: "recommended", label: "recommended 推荐" },
  { value: "active", label: "active 启用" },
  { value: "draft", label: "draft 草稿" },
  { value: "obsolete", label: "obsolete 废弃" },
  { value: "legacy", label: "legacy 历史" },
];

export default function ObservationVariablePage() {
  const [cropOptions, setCropOptions] = useState<SelectOption[]>([]);
  const [ontologyOptions, setOntologyOptions] = useState<SelectOption[]>([]);
  const [traitOptions, setTraitOptions] = useState<SelectOption[]>([]);
  const [methodOptions, setMethodOptions] = useState<SelectOption[]>([]);
  const [scaleOptions, setScaleOptions] = useState<SelectOption[]>([]);

  const loadRows = useCallback(async () => {
    const [options, rows] = await Promise.all([fetchObservationVariableOptions(), fetchObservationVariableRows()]);
    setCropOptions(options.crops);
    setOntologyOptions(options.ontologies);
    setTraitOptions(options.traits);
    setMethodOptions(options.methods);
    setScaleOptions(options.scales);
    return rows as unknown as Record<string, unknown>[];
  }, []);

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "id", label: "变量 ID", type: "text", required: true, placeholder: "如 PH_cm 或 CO_322:0000994" },
    { key: "name", label: "变量名称", type: "text", required: true, placeholder: "如 Plant Height by Ruler in cm" },
    { key: "trait_id", label: "Trait 性状", type: "select", required: true, options: traitOptions },
    { key: "method_id", label: "Method 方法", type: "select", required: true, options: methodOptions },
    { key: "scale_id", label: "Scale 尺度", type: "select", required: true, options: scaleOptions },
    {
      key: "crop_id",
      label: "作物",
      type: "select",
      options: [{ value: NONE_SELECT_VALUE, label: "不关联作物" }, ...cropOptions],
    },
    {
      key: "ontology_id",
      label: "本体",
      type: "select",
      options: [{ value: NONE_SELECT_VALUE, label: "不关联本体" }, ...ontologyOptions],
    },
    { key: "status", label: "状态", type: "select", options: statusOptions },
    { key: "default_value", label: "默认值", type: "text", placeholder: "采集表默认填充值" },
    { key: "growth_stage", label: "采集生育期", type: "text", placeholder: "如 flowering / V6 / R1" },
    { key: "scientist", label: "提交人", type: "text", placeholder: "维护人或科学家" },
    { key: "institution", label: "机构", type: "text", placeholder: "提交机构" },
    { key: "language", label: "语言", type: "text", placeholder: "如 zh / en" },
    { key: "submission_timestamp", label: "提交日期", type: "date" },
    { key: "pui", label: "变量 PUI", type: "text", placeholder: "永久唯一标识或 URI", colSpan: 2 },
    { key: "documentationurl", label: "文档地址", type: "text", placeholder: "https://...", colSpan: 2 },
  ], [cropOptions, methodOptions, ontologyOptions, scaleOptions, traitOptions]);

  return (
    <BrapiEntityPage
      icon={ClipboardList}
      iconBg="bg-gradient-to-br from-purple-500 to-indigo-600"
      title="ObservationVariable 采集变量"
      description="配置 Trait + Method + Scale 的采集变量，供田间采集模板和观测值引用"
      addLabel="新增变量"
      columns={[
        { key: "id", label: "变量 ID" },
        { key: "name", label: "变量名称" },
        { key: "trait_name", label: "Trait" },
        { key: "method_name", label: "Method" },
        {
          key: "scale_name",
          label: "Scale",
          render: (value, row) => `${value || "—"}${row.units ? ` / ${String(row.units)}` : ""}`,
        },
        { key: "commonCropName", label: "作物" },
        { key: "status", label: "状态" },
        { key: "growth_stage", label: "采集阶段" },
      ]}
      fields={fields}
      data={[]}
      stats={[{ label: "/brapi/v2/variables", value: "BrAPI", className: "bg-purple-50 text-purple-700 dark:bg-purple-400/10 dark:text-purple-200" }]}
      loadData={loadRows}
      createRecord={(payload) => createObservationVariableRow(payload) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updateObservationVariableRow(id, payload) as unknown as Promise<Record<string, unknown>>}
      deleteRecord={deleteObservationVariableRow}
    />
  );
}
