"use client";

import Link from "next/link";
import { useCallback, useMemo, useState } from "react";
import { Map, RotateCcw, Search } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField } from "@/components/brapi/BrapiEntityPage";
import { Badge } from "@/components/ui/badge";
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 {
  createGenomeMapRow,
  deleteGenomeMapRow,
  loadGenomeMapPageData,
  normalizeGenomeMapFormData,
  updateGenomeMapRow,
} from "../api";
import { NONE_SELECT_VALUE, type GenomeMapQuery, type SelectOption } from "../types";

const mapTypeOptions: SelectOption[] = [
  { value: "physical", label: "physical（物理图）" },
  { value: "genomic", label: "genomic（基因组图）" },
];

const emptyQuery = (): GenomeMapQuery => ({
  map_name: "",
  common_crop_name: NONE_SELECT_VALUE,
  type: NONE_SELECT_VALUE,
});

const optionOrNone = (label: string, options: SelectOption[]) => [
  { value: NONE_SELECT_VALUE, label },
  ...options,
];

export function GenomeMapTab() {
  const [cropOptions, setCropOptions] = useState<SelectOption[]>([]);
  const [draftQuery, setDraftQuery] = useState<GenomeMapQuery>(emptyQuery);
  const [appliedQuery, setAppliedQuery] = useState<GenomeMapQuery>(emptyQuery);

  const loadRows = useCallback(async () => {
    const { options, rows } = await loadGenomeMapPageData({ query: appliedQuery });
    setCropOptions(options.crops);
    return rows as unknown as Record<string, unknown>[];
  }, [appliedQuery]);

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "id", label: "Map ID", type: "text", readOnly: true, placeholder: "保存后由系统自动生成" },
    { key: "map_name", label: "图谱名称", type: "text", required: true, placeholder: "如 Maize IBM2" },
    {
      key: "map_pui",
      label: "Map PUI",
      type: "text",
      readOnly: true,
      placeholder: "保存后由系统自动生成",
    },
    {
      key: "common_crop_name",
      label: "作物",
      type: "select",
      options: optionOrNone("不关联作物", cropOptions),
    },
    { key: "scientific_name", label: "学名", type: "text", placeholder: "Zea mays" },
    {
      key: "type",
      label: "图谱类型",
      type: "select",
      options: optionOrNone("不指定", mapTypeOptions),
    },
    { key: "unit", label: "单位", type: "text", placeholder: "如 cM" },
    { key: "published_date", label: "发表日期", type: "date" },
    { key: "documentation_url", label: "文档 URL", type: "text", placeholder: "https://..." },
    { key: "comments", label: "备注", type: "textarea", colSpan: 2 },
  ], [cropOptions]);

  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 xl:grid-cols-4">
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">图谱名称</Label>
          <Input
            value={draftQuery.map_name ?? ""}
            onChange={(event) => setDraftQuery((current) => ({ ...current, map_name: event.target.value }))}
            placeholder="mapName 模糊匹配"
          />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">作物</Label>
          <Select
            value={draftQuery.common_crop_name ?? NONE_SELECT_VALUE}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, common_crop_name: value }))}
          >
            <SelectTrigger><SelectValue placeholder="全部" /></SelectTrigger>
            <SelectContent>
              <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>
          <Select
            value={draftQuery.type ?? NONE_SELECT_VALUE}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, type: value }))}
          >
            <SelectTrigger><SelectValue placeholder="全部" /></SelectTrigger>
            <SelectContent>
              <SelectItem value={NONE_SELECT_VALUE}>全部</SelectItem>
              {mapTypeOptions.map((option) => (
                <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>
      <div className="mt-3 flex flex-wrap 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>
  ), [draftQuery, cropOptions]);

  return (
    <BrapiEntityPage
      useEnhancedDialog
      icon={Map}
      iconBg="bg-gradient-to-br from-teal-500 to-cyan-600"
      title="GenomeMap 遗传图谱"
      description="维护遗传图谱主数据；可切换 Linkage Group Tab 跨图谱维护，或进入详情维护 Marker Position。"
      addLabel="新增图谱"
      columns={[
        {
          key: "map_name",
          label: "名称",
          render: (value, row) => {
            const id = String(row.id ?? row.mapDbId ?? "");
            const name = String(value ?? "—");
            if (!id) return name;
            return (
              <Link
                href={`/genotyping/genome-map/maps/${encodeURIComponent(id)}`}
                className="font-medium text-teal-600 hover:underline dark:text-teal-400"
              >
                {name}
              </Link>
            );
          },
        },
        { key: "common_crop_name", label: "作物" },
        { key: "type", label: "类型" },
        { key: "unit", label: "单位" },
        {
          key: "linkage_group_count",
          label: "连锁群",
          render: (value) => <Badge variant="outline">{Number(value ?? 0)}</Badge>,
        },
        {
          key: "marker_count",
          label: "Marker 数",
          render: (value) => <Badge variant="outline">{Number(value ?? 0)}</Badge>,
        },
      ]}
      fields={fields}
      data={[]}
      stats={[{
        label: "/brapi/v2/maps",
        value: "BrAPI",
        className: "bg-teal-50 text-teal-700 dark:bg-teal-400/10 dark:text-teal-200",
      }]}
      loadData={loadRows}
      fetchRecord={async (id) => {
        const { rows } = await loadGenomeMapPageData({ force: true });
        const row = rows.find((item) => item.id === id);
        if (!row) throw new Error("图谱不存在");
        return normalizeGenomeMapFormData(row);
      }}
      createRecord={(payload) => createGenomeMapRow(payload) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updateGenomeMapRow(id, payload) as unknown as Promise<Record<string, unknown>>}
      deleteRecord={deleteGenomeMapRow}
      renderQueryForm={renderQueryForm}
    />
  );
}
