"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { BookOpen } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField } from "@/components/brapi/BrapiEntityPage";
import { StudyContactsEditor } from "./components/StudyContactsEditor";
import { StudySeasonsEditor } from "./components/StudySeasonsEditor";
import { mapContactsFromApi, mapSeasonsFromApi } from "./components/studyRelationUtils";
import {
  createStudyRow,
  deleteStudyRow,
  enrichStudyRows,
  fetchStudyDetail,
  fetchStudyOptions,
  fetchStudyRows,
  updateStudyRow,
} from "./api";
import {
  NONE_SELECT_VALUE,
  type SelectOption,
  type StudyContactRow,
  type StudySeasonRow,
  type TrialSelectOption,
} from "./types";

export default function StudyPage() {
  const [cropOptions, setCropOptions] = useState<SelectOption[]>([]);
  const [locationOptions, setLocationOptions] = useState<SelectOption[]>([]);
  const [trialOptions, setTrialOptions] = useState<TrialSelectOption[]>([]);
  const [personOptions, setPersonOptions] = useState<SelectOption[]>([]);
  const [seasonOptions, setSeasonOptions] = useState<SelectOption[]>([]);

  const applyStudyOptions = useCallback((options: Awaited<ReturnType<typeof fetchStudyOptions>>) => {
    setCropOptions(options.crops);
    setLocationOptions(options.locations);
    setTrialOptions(options.trials);
    setPersonOptions(options.persons);
    setSeasonOptions(options.seasons);
    return options;
  }, []);

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

  const loadRows = useCallback(async () => {
    const [options, rows] = await Promise.all([fetchStudyOptions(), fetchStudyRows()]);
    applyStudyOptions(options);
    return enrichStudyRows(rows, options.trials) as unknown as Record<string, unknown>[];
  }, [applyStudyOptions]);

  const enrichSeasonLabels = useCallback((seasons: StudySeasonRow[], options: SelectOption[]) => {
    const labelById = new Map(options.map((option) => [option.value, option.label]));
    return seasons.map((season) => ({
      ...season,
      label: labelById.get(season.seasonDbId) ?? season.label,
    }));
  }, []);

  const fetchRecord = useCallback(
    async (id: string) => {
      const detail = await fetchStudyDetail(id);
      const studyContacts = detail.studyContacts ?? mapContactsFromApi(detail.contacts);
      const studySeasons = enrichSeasonLabels(
        detail.studySeasons ?? mapSeasonsFromApi(detail.seasons),
        seasonOptions,
      );

      return {
        ...detail,
        studyContacts,
        studySeasons,
      } as unknown as Record<string, unknown>;
    },
    [enrichSeasonLabels, seasonOptions],
  );

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "study_name", label: "研究名称", type: "text", required: true, placeholder: "如 2026 春季田间表型研究" },
    { key: "study_code", label: "研究编码", type: "text", placeholder: "如 ST-2026-SPRING" },
    {
      key: "study_type",
      label: "研究类型",
      type: "select",
      options: [
        { value: NONE_SELECT_VALUE, label: "不指定类型" },
        { value: "Field Trial", label: "Field Trial 田间试验" },
        { value: "Nursery", label: "Nursery 圃地研究" },
        { value: "Phenotyping", label: "Phenotyping 表型研究" },
        { value: "Genotyping", label: "Genotyping 基因型研究" },
        { value: "Observation", label: "Observation 观察研究" },
      ],
    },
    {
      key: "trial_id",
      label: "所属 Trial",
      type: "select",
      options: [{ value: NONE_SELECT_VALUE, label: "不关联 Trial" }, ...trialOptions],
    },
    {
      key: "location_id",
      label: "试验地点",
      type: "select",
      options: [{ value: NONE_SELECT_VALUE, label: "不关联地点" }, ...locationOptions],
    },
    {
      key: "crop_id",
      label: "作物（Common Crop Name）",
      type: "select",
      options: [{ value: NONE_SELECT_VALUE, label: "不指定作物" }, ...cropOptions],
    },
    {
      key: "active",
      label: "状态",
      type: "select",
      options: [
        { value: "true", label: "活跃" },
        { value: "false", label: "停用" },
      ],
    },
    { key: "start_date", label: "开始日期", type: "date" },
    { key: "end_date", label: "结束日期", type: "date" },
    { key: "studypui", label: "Study PUI", type: "text", placeholder: "永久唯一标识" },
    { key: "documentationurl", label: "文档地址", type: "text", placeholder: "https://..." },
    { key: "license", label: "许可证", type: "text", placeholder: "如 CC-BY-4.0" },
    { key: "cultural_practices", label: "栽培措施", type: "textarea", placeholder: "播种、施肥、灌溉、管理方式等", colSpan: 2 },
    { key: "observation_units_description", label: "观测单元说明", type: "textarea", placeholder: "观测单元数量、布局、重复等", colSpan: 2 },
    { key: "study_description", label: "研究说明", type: "textarea", placeholder: "研究目标、设计说明、数据采集范围等", colSpan: 2 },
  ], [cropOptions, locationOptions, trialOptions]);

  return (
    <BrapiEntityPage
      icon={BookOpen}
      iconBg="bg-gradient-to-br from-emerald-500 to-teal-600"
      title="Study 研究"
      description="对接 /studies、/people、/seasons；联系人(study_contact)、季节(study_season)随 Study 保存"
      addLabel="新增研究"
      useEnhancedDialog
      columns={[
        { key: "studyDbId", label: "研究 ID" },
        { key: "study_name", label: "研究名称" },
        { key: "study_code", label: "研究编码" },
        { key: "study_type", label: "类型" },
        { key: "trial_name", label: "Trial" },
        { key: "program_name", label: "项目" },
        { key: "location_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: "seasons",
          label: "季节数",
          render: (value) => {
            const count = Array.isArray(value) ? value.length : 0;
            return count > 0 ? String(count) : "0";
          },
        },
        { key: "start_date", label: "开始日期" },
        { key: "active", label: "状态", render: (value) => value === true ? "活跃" : value === false ? "停用" : "—" },
      ]}
      fields={fields}
      data={[]}
      stats={[
        { label: "studies", value: "CRUD", className: "bg-emerald-50 text-emerald-700 dark:bg-emerald-400/10 dark:text-emerald-200" },
        { label: "people", value: "GET", className: "bg-violet-50 text-violet-700 dark:bg-violet-400/10 dark:text-violet-200" },
        { label: "seasons", value: "GET", className: "bg-sky-50 text-sky-700 dark:bg-sky-400/10 dark:text-sky-200" },
      ]}
      loadData={loadRows}
      fetchRecord={fetchRecord}
      createRecord={(payload) => createStudyRow({
        ...payload,
        studyContacts: payload.studyContacts ?? [],
        studySeasons: payload.studySeasons ?? [],
      }) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updateStudyRow(id, {
        ...payload,
        studyContacts: payload.studyContacts ?? [],
        studySeasons: payload.studySeasons ?? [],
      }) as unknown as Promise<Record<string, unknown>>}
      deleteRecord={deleteStudyRow}
      renderFormExtra={({ formData, updateFormBatch }) => {
        const studyContacts = (formData.studyContacts as StudyContactRow[] | undefined) ?? [];
        const studySeasons = (formData.studySeasons as StudySeasonRow[] | undefined) ?? [];

        return (
          <>
            <StudyContactsEditor
              contacts={studyContacts}
              personOptions={personOptions}
              onChange={(contacts) => updateFormBatch({ studyContacts: contacts })}
            />
            <StudySeasonsEditor
              seasons={studySeasons}
              seasonOptions={seasonOptions}
              onChange={(seasons) => updateFormBatch({ studySeasons: seasons })}
            />
          </>
        );
      }}
    />
  );
}
