"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { ListChecks } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField } from "@/components/brapi/BrapiEntityPage";
import { fetchAttributeOptions } from "../attributeApi";
import {
  createAttributeValueRow,
  fetchAttributeValueDetail,
  fetchAttributeValueRows,
  normalizeAttributeValueFormData,
  updateAttributeValueRow,
} from "../attributeValueApi";
import { fetchGermplasmRows } from "../api";
import { NONE_SELECT_VALUE, type SelectOption } from "../attributeTypes";

interface GermplasmAttributeValueTabProps {
  scopeGermplasmDbId?: string;
}

export function GermplasmAttributeValueTab({ scopeGermplasmDbId }: GermplasmAttributeValueTabProps = {}) {
  const [germplasmOptions, setGermplasmOptions] = useState<SelectOption[]>([]);
  const [attributeOptions, setAttributeOptions] = useState<SelectOption[]>([]);

  const loadSelectOptions = useCallback(async () => {
    const [germplasmRows, attributes] = await Promise.all([
      fetchGermplasmRows().catch(() => []),
      fetchAttributeOptions().catch(() => []),
    ]);

    setGermplasmOptions(
      germplasmRows.map((row) => ({
        value: row.id,
        label: row.default_display_name || row.germplasm_name || row.id,
      })).filter((option) => option.value),
    );
    setAttributeOptions(attributes);
    return { germplasmOptions: germplasmRows, attributeOptions: attributes };
  }, []);

  useEffect(() => {
    loadSelectOptions().catch(() => {
      // 下拉选项加载失败时不阻断列表页
    });
  }, [loadSelectOptions]);

  const loadRows = useCallback(async () => {
    await loadSelectOptions();
    const rows = await fetchAttributeValueRows(scopeGermplasmDbId);
    return rows as unknown as Record<string, unknown>[];
  }, [loadSelectOptions, scopeGermplasmDbId]);

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

  const fields = useMemo<BrapiFormField[]>(() => {
    const germplasmField: BrapiFormField = scopeGermplasmDbId
      ? { key: "germplasm_id", label: "种质材料", type: "text", required: true, readOnly: true }
      : {
        key: "germplasm_id",
        label: "种质材料",
        type: "select",
        required: true,
        placeholder: germplasmOptions.length > 0 ? "请选择种质" : "请先在「种质列表」Tab 创建材料",
        options: [{ value: NONE_SELECT_VALUE, label: "请选择种质" }, ...germplasmOptions],
      };

    return [
      germplasmField,
    {
      key: "attribute_id",
      label: "属性定义",
      type: "select",
      required: true,
      placeholder: attributeOptions.length > 0 ? "请选择属性" : "请先在「属性定义」Tab 创建属性",
      options: [{ value: NONE_SELECT_VALUE, label: "请选择属性" }, ...attributeOptions],
    },
    {
      key: "value",
      label: "属性值",
      type: "text",
      required: true,
      placeholder: "按属性数据类型填写实际取值",
    },
    { key: "determined_date", label: "测定日期", type: "date" },
    ];
  }, [attributeOptions, germplasmOptions, scopeGermplasmDbId]);

  const defaultFormValues = useMemo(
    () => (scopeGermplasmDbId ? { germplasm_id: scopeGermplasmDbId } : undefined),
    [scopeGermplasmDbId],
  );

  const scopedColumns = useMemo(() => {
    const columns = [
      { key: "attributeValueDbId", label: "属性值 ID" },
      ...(scopeGermplasmDbId ? [] : [{ key: "germplasmName", label: "种质" }]),
      { key: "attributeName", label: "属性" },
      { key: "value", label: "取值" },
      { key: "determined_date", label: "测定日期" },
    ];
    return columns;
  }, [scopeGermplasmDbId]);

  return (
    <BrapiEntityPage
      icon={ListChecks}
      iconBg="bg-gradient-to-br from-indigo-500 to-blue-600"
      title={scopeGermplasmDbId ? "属性值" : "Germplasm Attribute Value 属性值"}
      description={scopeGermplasmDbId
        ? "维护当前种质的扩展属性取值（germplasm_attribute_value）"
        : "记录某个种质在某个属性上的实际取值（germplasm_attribute_value）"}
      addLabel="新增属性值"
      useEnhancedDialog
      defaultFormValues={defaultFormValues}
      fetchRecord={fetchRecord}
      columns={scopedColumns}
      fields={fields}
      data={[]}
      stats={[
        {
          label: "/brapi/v2/attributevalues",
          value: "BrAPI",
          className: "bg-indigo-50 text-indigo-700 dark:bg-indigo-400/10 dark:text-indigo-200",
        },
      ]}
      loadData={loadRows}
      createRecord={(payload) => createAttributeValueRow({
        ...payload,
        germplasm_id: scopeGermplasmDbId ?? payload.germplasm_id,
      }) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updateAttributeValueRow(id, {
        ...payload,
        germplasm_id: scopeGermplasmDbId ?? payload.germplasm_id,
      }) as unknown as Promise<Record<string, unknown>>}
    />
  );
}
