"use client";

import Link from "next/link";
import { Suspense, useCallback, useEffect, useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import { Dna, ListChecks, RotateCcw, Search, Tags } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField } from "@/components/brapi/BrapiEntityPage";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  createGermplasmRow,
  deleteGermplasmRow,
  fetchGermplasmDetail,
  fetchGermplasmOptions,
  fetchGermplasmRows,
  normalizeGermplasmFormData,
  updateGermplasmRow,
} from "./api";
import { GermplasmAttributeTab } from "./components/GermplasmAttributeTab";
import { GermplasmAttributeValueTab } from "./components/GermplasmAttributeValueTab";
import { NONE_SELECT_VALUE, type GermplasmQuery, type SelectOption } from "./types";

const emptyQuery = (): GermplasmQuery => ({
  crop_id: NONE_SELECT_VALUE,
  germplasm_name: "",
  accession_number: "",
  germplasmpui: "",
  synonym: "",
});

export default function GermplasmPage() {
  return (
    <Suspense fallback={<div className="p-6 text-sm text-slate-500">加载种质页…</div>}>
      <GermplasmPageContent />
    </Suspense>
  );
}

function GermplasmPageContent() {
  const searchParams = useSearchParams();
  const initialTab = useMemo(() => {
    const tab = searchParams.get("tab");
    if (tab === "attributes" || tab === "attribute-values") return tab;
    return "germplasm";
  }, [searchParams]);

  const [activeTab, setActiveTab] = useState(initialTab);
  const [cropOptions, setCropOptions] = useState<SelectOption[]>([]);
  const [breedingMethodOptions, setBreedingMethodOptions] = useState<SelectOption[]>([]);
  const [draftQuery, setDraftQuery] = useState<GermplasmQuery>(emptyQuery);
  const [appliedQuery, setAppliedQuery] = useState<GermplasmQuery>(emptyQuery);

  const applyGermplasmOptions = useCallback((options: Awaited<ReturnType<typeof fetchGermplasmOptions>>) => {
    setCropOptions(options.crops);
    setBreedingMethodOptions(options.breedingMethods);
    return options;
  }, []);

  useEffect(() => {
    setActiveTab(initialTab);
  }, [initialTab]);

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

  const loadRows = useCallback(async () => {
    const query: GermplasmQuery = {
      ...appliedQuery,
      crop_id: appliedQuery.crop_id === NONE_SELECT_VALUE ? undefined : appliedQuery.crop_id,
    };
    const [options, rows] = await Promise.all([fetchGermplasmOptions(), fetchGermplasmRows(query)]);
    applyGermplasmOptions(options);
    return rows as unknown as Record<string, unknown>[];
  }, [applyGermplasmOptions, appliedQuery]);

  const renderQueryForm = useCallback(() => (
    <div className="rounded-xl border border-slate-200 bg-white p-4 dark:border-slate-800 dark:bg-slate-950">
      <div className="grid gap-3 md:grid-cols-2 lg:grid-cols-3">
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">作物</Label>
          <Select
            value={draftQuery.crop_id ?? NONE_SELECT_VALUE}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, crop_id: value }))}
          >
            <SelectTrigger><SelectValue placeholder="全部作物" /></SelectTrigger>
            <SelectContent position="popper" className="z-[110] max-h-60">
              <SelectItem value={NONE_SELECT_VALUE}>全部作物</SelectItem>
              {cropOptions.map((option) => (
                <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">种质名称</Label>
          <Input
            value={draftQuery.germplasm_name ?? ""}
            onChange={(event) => setDraftQuery((current) => ({ ...current, germplasm_name: event.target.value }))}
            placeholder="子串匹配"
          />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">登录号</Label>
          <Input
            value={draftQuery.accession_number ?? ""}
            onChange={(event) => setDraftQuery((current) => ({ ...current, accession_number: event.target.value }))}
            placeholder="Accession 子串匹配"
          />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">Germplasm PUI</Label>
          <Input
            value={draftQuery.germplasmpui ?? ""}
            onChange={(event) => setDraftQuery((current) => ({ ...current, germplasmpui: event.target.value }))}
            placeholder="PUI 子串匹配"
          />
        </div>
        <div className="space-y-1.5 md:col-span-2">
          <Label className="text-xs text-slate-500">别名（Synonym）</Label>
          <Input
            value={draftQuery.synonym ?? ""}
            onChange={(event) => setDraftQuery((current) => ({ ...current, synonym: event.target.value }))}
            placeholder="走后端 search/germplasm 精确匹配"
          />
        </div>
      </div>
      <div className="mt-3 flex justify-end gap-2">
        <Button
          type="button"
          variant="outline"
          className="gap-2"
          onClick={() => {
            const reset = emptyQuery();
            setDraftQuery(reset);
            setAppliedQuery(reset);
          }}
        >
          <RotateCcw className="h-4 w-4" />
          重置
        </Button>
        <Button type="button" className="gap-2" onClick={() => setAppliedQuery({ ...draftQuery })}>
          <Search className="h-4 w-4" />
          查询
        </Button>
      </div>
    </div>
  ), [cropOptions, draftQuery]);

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

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "germplasm_name", label: "种质名称", type: "text", required: true, placeholder: "如 B73 / Mo17 / CASS-0001" },
    { key: "default_display_name", label: "展示名称", type: "text", placeholder: "页面和报表优先展示的名称" },
    { key: "accession_number", label: "登录号", type: "text", placeholder: "如 CASS-0001" },
    { key: "germplasmpui", label: "Germplasm PUI", type: "text", placeholder: "永久唯一标识" },
    {
      key: "crop_id",
      label: "作物（Common Crop Name）",
      type: "select",
      options: [{ value: NONE_SELECT_VALUE, label: "不关联作物" }, ...cropOptions],
    },
    { key: "genus", label: "属", type: "text", placeholder: "如 Zea" },
    { key: "species", label: "种", type: "text", placeholder: "如 mays" },
    { key: "species_authority", label: "种命名人", type: "text" },
    { key: "subtaxa", label: "亚分类", type: "text" },
    { key: "subtaxa_authority", label: "亚分类命名人", type: "text" },
    {
      key: "country_of_origin_code",
      label: "来源国家",
      type: "text",
      placeholder: "如 CHN / USA / 中国",
    },
    { key: "acquisition_date", label: "获取日期", type: "date" },
    { key: "collection", label: "所属集合", type: "text", placeholder: "如 Maize Core Collection" },
    {
      key: "breeding_method_id",
      label: "育种方法",
      type: "select",
      placeholder: breedingMethodOptions.length > 0 ? "请选择育种方法" : "暂无育种方法，请先在「育种方法」页维护",
      options: [{ value: NONE_SELECT_VALUE, label: "不指定育种方法" }, ...breedingMethodOptions],
    },
    { key: "acquisition_source_code", label: "获取来源代码", type: "number" },
    { key: "biological_status_of_accession_code", label: "生物状态代码", type: "number" },
    { key: "mls_status", label: "MLS 状态", type: "number" },
    { key: "seed_source", label: "种子来源", type: "text" },
    { key: "documentationurl", label: "文档地址", type: "text", placeholder: "https://..." },
    { key: "seed_source_description", label: "种子来源说明", type: "textarea", colSpan: 2 },
    { key: "germplasm_preprocessing", label: "预处理说明", type: "textarea", colSpan: 2 },
  ], [cropOptions, breedingMethodOptions]);

  return (
    <Tabs value={activeTab} onValueChange={setActiveTab} className="flex min-h-full flex-col gap-4">
      <TabsList className="w-full justify-start overflow-x-auto rounded-lg border bg-white p-1 dark:border-slate-800 dark:bg-slate-950 sm:w-fit">
        <TabsTrigger value="germplasm" className="gap-2">
          <Dna className="h-4 w-4" />
          种质列表
        </TabsTrigger>
        <TabsTrigger value="attributes" className="gap-2">
          <Tags className="h-4 w-4" />
          属性定义
        </TabsTrigger>
        <TabsTrigger value="attribute-values" className="gap-2">
          <ListChecks className="h-4 w-4" />
          属性值
        </TabsTrigger>
      </TabsList>

      <TabsContent value="germplasm" className="mt-0 min-h-0 flex-1">
        <BrapiEntityPage
          icon={Dna}
          iconBg="bg-gradient-to-br from-teal-500 to-emerald-600"
          title="Germplasm 种质"
          description="维护品种、品系、材料、资源材料等种质核心对象，并关联作物与育种方法"
          addLabel="新增种质"
          useEnhancedDialog
          fetchRecord={fetchRecord}
          columns={[
            { key: "id", label: "种质 ID" },
            {
              key: "germplasm_name",
              label: "种质名称",
              render: (value, row) => {
                const id = String(row.id ?? row.germplasmDbId ?? "");
                const name = String(value ?? row.default_display_name ?? "—");
                if (!id) return name;
                return (
                  <Link
                    href={`/germplasm/germplasm/${encodeURIComponent(id)}`}
                    className="font-medium text-teal-600 hover:underline dark:text-teal-400"
                  >
                    {name}
                  </Link>
                );
              },
            },
            { key: "default_display_name", label: "展示名称" },
            { key: "accession_number", label: "登录号" },
            { key: "country_of_origin_code", label: "来源国家" },
            { key: "crop_name", label: "作物" },
            { key: "genus", label: "属" },
            { key: "species", label: "种" },
            {
              key: "breeding_method_name",
              label: "育种方法",
              render: (value, row) => value ? String(value) : String(row.breeding_method_id ?? "—"),
            },
          ]}
          fields={fields}
          data={[]}
          stats={[
            { label: "/brapi/v2/germplasm", value: "BrAPI", className: "bg-teal-50 text-teal-700 dark:bg-teal-400/10 dark:text-teal-200" },
            { label: "/brapi/v2/commoncropnames", value: "GET", className: "bg-amber-50 text-amber-700 dark:bg-amber-400/10 dark:text-amber-200" },
            { label: "/brapi/v2/breedingmethods", value: "GET", className: "bg-violet-50 text-violet-700 dark:bg-violet-400/10 dark:text-violet-200" },
          ]}
          loadData={loadRows}
          renderQueryForm={() => renderQueryForm()}
          createRecord={(payload) => createGermplasmRow(payload) as unknown as Promise<Record<string, unknown>>}
          updateRecord={(id, payload) => updateGermplasmRow(id, payload) as unknown as Promise<Record<string, unknown>>}
          deleteRecord={deleteGermplasmRow}
        />
      </TabsContent>

      <TabsContent value="attributes" className="mt-0 min-h-0 flex-1">
        <GermplasmAttributeTab />
      </TabsContent>

      <TabsContent value="attribute-values" className="mt-0 min-h-0 flex-1">
        <GermplasmAttributeValueTab />
      </TabsContent>
    </Tabs>
  );
}
