"use client";

import Link from "next/link";
import { useCallback, useMemo, useState } from "react";
import { FlaskConical } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField } from "@/components/brapi/BrapiEntityPage";
import { Button } from "@/components/ui/button";
import { TrialContactsEditor } from "./components/TrialContactsEditor";
import { TrialPublicationsEditor } from "./components/TrialPublicationsEditor";
import { mapContactsFromApi, mapPublicationsFromApi } from "./components/trialRelationUtils";
import {
  createTrialRow,
  deleteTrialRow,
  fetchTrialDetail,
  fetchTrialOptions,
  fetchTrialRows,
  updateTrialRow,
} from "./api";
import { NONE_SELECT_VALUE, type SelectOption, type TrialContactRow, type TrialPublicationRow } from "./types";

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

  const loadRows = useCallback(async () => {
    const [options, rows] = await Promise.all([fetchTrialOptions(), fetchTrialRows()]);
    setCropOptions(options.crops);
    setProgramOptions(options.programs);
    setPersonOptions(options.persons);
    return rows as unknown as Record<string, unknown>[];
  }, []);

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "trial_name", label: "试验名称", type: "text", required: true, placeholder: "如 2026 Multi Location Yield Trial" },
    {
      key: "program_id",
      label: "所属项目 (program)",
      type: "select",
      options: [{ value: NONE_SELECT_VALUE, label: "不关联项目" }, ...programOptions],
    },
    {
      key: "crop_id",
      label: "作物 (commonCropName)",
      type: "select",
      options: [{ value: NONE_SELECT_VALUE, label: "不关联作物（已选项目时由项目带出）" }, ...cropOptions],
    },
    {
      key: "active",
      label: "状态",
      type: "select",
      options: [
        { value: "true", label: "活跃" },
        { value: "false", label: "停用" },
      ],
    },
    { key: "trialpui", label: "Trial PUI", type: "text", placeholder: "永久唯一标识" },
    { key: "start_date", label: "开始日期", type: "date" },
    { key: "end_date", label: "结束日期", type: "date" },
    { key: "documentationurl", label: "文档地址", type: "text", placeholder: "https://..." },
    { key: "trial_description", label: "试验说明", type: "textarea", placeholder: "试验目标、设计说明、参试地点范围等", colSpan: 2 },
  ], [cropOptions, programOptions]);

  const fetchRecord = useCallback(
    async (id: string) => {
      const detail = await fetchTrialDetail(id);
      return {
        ...detail,
        trialContacts: detail.trialContacts ?? mapContactsFromApi(detail.contacts),
        trialPublications: detail.trialPublications ?? mapPublicationsFromApi(detail.publications),
      } as unknown as Record<string, unknown>;
    },
    [],
  );

  return (
    <BrapiEntityPage
      icon={FlaskConical}
      iconBg="bg-gradient-to-br from-indigo-500 to-violet-600"
      title="Trial 试验"
      description="对接 /trials、/programs、/people、/commoncropnames；联系人(trial_contact)、出版物(trial_publication)随 Trial 保存"
      addLabel="新增试验"
      useEnhancedDialog
      columns={[
        { key: "trialDbId", label: "试验 ID" },
        { key: "trial_name", label: "试验名称" },
        { key: "program_name", label: "项目" },
        { key: "crop_name", label: "作物" },
        {
          key: "contacts",
          label: "联系人数",
          render: (value) => {
            const count = Array.isArray(value) ? value.length : 0;
            return count > 0 ? String(count) : "0";
          },
        },
        {
          key: "publications",
          label: "出版物数",
          render: (value) => {
            const count = Array.isArray(value) ? value.length : 0;
            return count > 0 ? String(count) : "0";
          },
        },
        { key: "start_date", label: "开始日期" },
        { key: "end_date", label: "结束日期" },
        { key: "active", label: "状态", render: (value) => value === true ? "活跃" : value === false ? "停用" : "—" },
        {
          key: "id",
          label: "详情",
          render: (_value, row) => {
            const id = String(row.id ?? row.trialDbId ?? "");
            if (!id) return <span className="text-slate-300">—</span>;
            return (
              <Button variant="link" className="h-auto p-0 text-indigo-600 dark:text-indigo-300" asChild>
                <Link href={`/project/trial/${encodeURIComponent(id)}`}>查看详情</Link>
              </Button>
            );
          },
        },
      ]}
      fields={fields}
      data={[]}
      stats={[
        { label: "trials", value: "CRUD", className: "bg-indigo-50 text-indigo-700 dark:bg-indigo-400/10 dark:text-indigo-200" },
        { label: "programs", value: "GET", className: "bg-blue-50 text-blue-700 dark:bg-blue-400/10 dark:text-blue-200" },
        { label: "people", value: "GET", className: "bg-violet-50 text-violet-700 dark:bg-violet-400/10 dark:text-violet-200" },
        { label: "commoncropnames", value: "GET", className: "bg-amber-50 text-amber-700 dark:bg-amber-400/10 dark:text-amber-200" },
      ]}
      loadData={loadRows}
      fetchRecord={fetchRecord}
      createRecord={(payload) => createTrialRow({
        ...payload,
        trialContacts: payload.trialContacts ?? [],
        trialPublications: payload.trialPublications ?? [],
      }) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updateTrialRow(id, payload) as unknown as Promise<Record<string, unknown>>}
      deleteRecord={deleteTrialRow}
      renderFormExtra={({ formData, updateFormBatch }) => {
        const trialContacts = (formData.trialContacts as TrialContactRow[] | undefined) ?? [];
        const trialPublications = (formData.trialPublications as TrialPublicationRow[] | undefined) ?? [];

        return (
          <>
            <TrialContactsEditor
              contacts={trialContacts}
              personOptions={personOptions}
              onChange={(contacts) => updateFormBatch({ trialContacts: contacts })}
            />
            <TrialPublicationsEditor
              publications={trialPublications}
              onChange={(publications) => updateFormBatch({ trialPublications: publications })}
            />
          </>
        );
      }}
    />
  );
}
