"use client";

import { useCallback, useMemo, useState } from "react";
import { Database } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField } from "@/components/brapi/BrapiEntityPage";
import {
  createObservationUnitRow,
  fetchObservationUnitOptions,
  fetchObservationUnitRows,
  updateObservationUnitRow,
} from "./api";
import { NONE_SELECT_VALUE, type SelectOption } from "./types";

const levelOptions: SelectOption[] = [
  { value: "field", label: "field 田块" },
  { value: "block", label: "block 区组" },
  { value: "plot", label: "plot 小区" },
  { value: "plant", label: "plant 单株" },
  { value: "sample", label: "sample 样品" },
];

export default function ObservationUnitPage() {
  const [studyOptions, setStudyOptions] = useState<SelectOption[]>([]);
  const [germplasmOptions, setGermplasmOptions] = useState<SelectOption[]>([]);

  const loadRows = useCallback(async () => {
    const [options, rows] = await Promise.all([fetchObservationUnitOptions(), fetchObservationUnitRows()]);
    setStudyOptions(options.studies);
    setGermplasmOptions(options.germplasms);
    return rows as unknown as Record<string, unknown>[];
  }, []);

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "id", label: "观测单元 ID", type: "text", required: true, placeholder: "如 ou-plot-001" },
    { key: "observation_unit_name", label: "单元名称", type: "text", required: true, placeholder: "如 Plot 001" },
    {
      key: "study_id",
      label: "Study",
      type: "select",
      options: [{ value: NONE_SELECT_VALUE, label: "不关联 Study" }, ...studyOptions],
    },
    {
      key: "germplasm_id",
      label: "材料",
      type: "select",
      options: [{ value: NONE_SELECT_VALUE, label: "不关联材料" }, ...germplasmOptions],
    },
    { key: "level", label: "层级", type: "select", required: true, options: levelOptions },
    { key: "level_order", label: "层级顺序", type: "number", placeholder: "如 plot=1, plant=2" },
    { key: "row", label: "行坐标", type: "text", placeholder: "如 1" },
    { key: "col", label: "列坐标", type: "text", placeholder: "如 1" },
  ], [germplasmOptions, studyOptions]);

  return (
    <BrapiEntityPage
      icon={Database}
      iconBg="bg-gradient-to-br from-violet-500 to-purple-600"
      title="ObservationUnit 观测单元"
      description="管理田间观测对象，关联 Study、材料、层级和行列坐标"
      addLabel="新增观测单元"
      columns={[
        { key: "observationUnitDbId", label: "单元 ID" },
        { key: "observation_unit_name", label: "单元名称" },
        { key: "study_id", label: "Study" },
        { key: "germplasm_id", label: "材料" },
        { key: "level", label: "层级" },
        { key: "row", label: "行" },
        { key: "col", label: "列" },
      ]}
      fields={fields}
      data={[]}
      stats={[{ label: "/brapi/v2/observationunits", value: "BrAPI", className: "bg-purple-50 text-purple-700 dark:bg-purple-400/10 dark:text-purple-200" }]}
      loadData={loadRows}
      createRecord={(payload) => createObservationUnitRow(payload) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updateObservationUnitRow(id, payload) as unknown as Promise<Record<string, unknown>>}
    />
  );
}
