"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { Tags } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField } from "@/components/brapi/BrapiEntityPage";
import {
  ATTRIBUTE_DATA_TYPE_OPTIONS,
  NONE_SELECT_VALUE,
  type SelectOption,
} from "../attributeTypes";
import {
  createAttributeRow,
  fetchAttributeDetail,
  fetchAttributeFormOptions,
  fetchAttributeRows,
  normalizeAttributeFormData,
  updateAttributeRow,
} from "../attributeApi";

export function GermplasmAttributeTab() {
  const [cropOptions, setCropOptions] = useState<SelectOption[]>([]);

  useEffect(() => {
    let mounted = true;
    fetchAttributeFormOptions()
      .then((options) => {
        if (mounted) setCropOptions(options.crops);
      })
      .catch(() => {
        // 下拉选项加载失败时不阻断列表页
      });
    return () => {
      mounted = false;
    };
  }, []);

  const loadRows = useCallback(async () => {
    const [options, rows] = await Promise.all([fetchAttributeFormOptions(), fetchAttributeRows()]);
    setCropOptions(options.crops);
    return rows as unknown as Record<string, unknown>[];
  }, []);

  const fetchRecord = useCallback(async (id: string) => {
    const detail = await fetchAttributeDetail(id);
    return normalizeAttributeFormData(detail);
  }, []);

  const fields = useMemo<BrapiFormField[]>(() => [
    {
      key: "attributeName",
      label: "属性名称",
      type: "text",
      required: true,
      placeholder: "如 籽粒颜色 / 抗病基因 / 熟期类型",
    },
    {
      key: "attributeCategory",
      label: "属性分类",
      type: "text",
      placeholder: "如 Morphological / Genetic / Quality",
    },
    {
      key: "dataType",
      label: "数据类型",
      type: "select",
      required: true,
      options: [{ value: NONE_SELECT_VALUE, label: "请选择数据类型" }, ...ATTRIBUTE_DATA_TYPE_OPTIONS],
    },
    {
      key: "crop_id",
      label: "适用作物",
      type: "select",
      options: [{ value: NONE_SELECT_VALUE, label: "不限定作物" }, ...cropOptions],
    },
    { key: "attributePUI", label: "属性 PUI", type: "text", placeholder: "永久唯一标识（可选）" },
    {
      key: "attributeDescription",
      label: "属性说明",
      type: "textarea",
      placeholder: "描述该属性的业务含义与取值说明",
      colSpan: 2,
    },
  ], [cropOptions]);

  return (
    <BrapiEntityPage
      icon={Tags}
      iconBg="bg-gradient-to-br from-violet-500 to-purple-600"
      title="Germplasm Attribute 属性定义"
      description="维护材料可有哪些稳定属性（germplasm_attribute_definition），供属性值录入时选择"
      addLabel="新增属性定义"
      useEnhancedDialog
      fetchRecord={fetchRecord}
      columns={[
        { key: "attributeDbId", label: "属性 ID" },
        { key: "attributeName", label: "属性名称" },
        { key: "attributeCategory", label: "分类" },
        {
          key: "dataType",
          label: "数据类型",
          render: (value) => (value ? String(value) : "—"),
        },
        { key: "commonCropName", label: "适用作物" },
        {
          key: "attributeDescription",
          label: "说明",
          render: (value) => {
            const text = String(value ?? "").trim();
            if (!text) return "—";
            return text.length > 40 ? `${text.slice(0, 40)}…` : text;
          },
        },
      ]}
      fields={fields}
      data={[]}
      stats={[
        {
          label: "/brapi/v2/attributes",
          value: "BrAPI",
          className: "bg-violet-50 text-violet-700 dark:bg-violet-400/10 dark:text-violet-200",
        },
      ]}
      loadData={loadRows}
      createRecord={(payload) => createAttributeRow(payload) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updateAttributeRow(id, payload) as unknown as Promise<Record<string, unknown>>}
    />
  );
}
