"use client";

import { useCallback, useMemo, useState } from "react";
import { Briefcase } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField } from "@/components/brapi/BrapiEntityPage";
import { createProgramRow, deleteProgramRow, fetchProgramOptions, fetchProgramRows, updateProgramRow } from "./api";
import { NONE_SELECT_VALUE, type SelectOption } from "./types";

export default function ProgramPage() {
  const [cropOptions, setCropOptions] = useState<SelectOption[]>([]);
  const [personOptions, setPersonOptions] = useState<SelectOption[]>([]);

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

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "name", label: "项目名称", type: "text", required: true, placeholder: "如 Maize Yield Improvement Program" },
    { key: "abbreviation", label: "缩写", type: "text", placeholder: "如 MYIP" },
    {
      key: "crop_id",
      label: "作物",
      type: "select",
      options: [{ value: NONE_SELECT_VALUE, label: "不关联作物" }, ...cropOptions],
    },
    {
      key: "lead_person_id",
      label: "负责人",
      type: "select",
      options: [{ value: NONE_SELECT_VALUE, label: "不指定负责人" }, ...personOptions],
    },
    { key: "program_type", label: "项目类型", type: "number", placeholder: "可选数字枚举" },
    { key: "funding_information", label: "资金信息", type: "text", placeholder: "基金、课题或合同来源" },
    { key: "documentationurl", label: "文档地址", type: "text", placeholder: "https://..." },
    { key: "objective", label: "项目目标", type: "textarea", placeholder: "项目目标、育种方向或研究范围", colSpan: 2 },
  ], [cropOptions, personOptions]);

  return (
    <BrapiEntityPage
      icon={Briefcase}
      iconBg="bg-gradient-to-br from-blue-500 to-indigo-600"
      title="Program 项目"
      description="维护育种项目、科研项目、基金项目等高层组织，并关联作物和负责人"
      addLabel="新增项目"
      columns={[
        { key: "programDbId", label: "项目 ID" },
        { key: "name", label: "项目名称" },
        { key: "abbreviation", label: "缩写" },
        { key: "crop_name", label: "作物" },
        { key: "lead_person_name", label: "负责人" },
        { key: "objective", label: "目标" },
        { key: "funding_information", label: "资金信息" },
      ]}
      fields={fields}
      data={[]}
      stats={[{ label: "/brapi/v2/programs", value: "BrAPI", className: "bg-blue-50 text-blue-700 dark:bg-blue-400/10 dark:text-blue-200" }]}
      loadData={loadRows}
      createRecord={(payload) => createProgramRow(payload) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updateProgramRow(id, payload) as unknown as Promise<Record<string, unknown>>}
      deleteRecord={deleteProgramRow}
    />
  );
}
