"use client";

import Link from "next/link";
import { useCallback, useMemo, useState } from "react";
import { Layers, RotateCcw, Search } 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 {
  createReferenceSetRow,
  deleteReferenceSetRow,
  fetchReferenceSetDetail,
  loadReferenceSetPageData,
  normalizeReferenceSetFormData,
  updateReferenceSetRow,
} from "../api";
import { boolLabel, optionOrNone, warnMd5Checksum } from "../referenceUtils";
import { NONE_SELECT_VALUE, type ReferenceSetQuery, type SelectOption } from "../types";

const booleanOptions: SelectOption[] = [
  { value: NONE_SELECT_VALUE, label: "不指定" },
  { value: "true", label: "是" },
  { value: "false", label: "否" },
];

const emptyQuery = (): ReferenceSetQuery => ({
  reference_set_name: "",
  assembly_pui: "",
});

export function ReferenceSetTab() {
  const [germplasmOptions, setGermplasmOptions] = useState<SelectOption[]>([]);
  const [draftQuery, setDraftQuery] = useState<ReferenceSetQuery>(emptyQuery);
  const [appliedQuery, setAppliedQuery] = useState<ReferenceSetQuery>(emptyQuery);

  const loadRows = useCallback(async () => {
    const { options, referenceSets } = await loadReferenceSetPageData({ referenceSetQuery: appliedQuery });
    setGermplasmOptions(options.germplasm);
    return referenceSets as unknown as Record<string, unknown>[];
  }, [appliedQuery]);

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

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "id", label: "ReferenceSet ID", type: "text", placeholder: "留空则系统自动生成（导入时可指定）" },
    {
      key: "reference_set_name",
      label: "参考集合名称",
      type: "text",
      required: true,
      placeholder: "如 Maize B73 v4",
    },
    { key: "assembly_pui", label: "Assembly PUI", type: "text", placeholder: "GA4GH 永久标识" },
    { key: "description", label: "说明", type: "textarea", colSpan: 2, placeholder: "参考集合说明" },
    { key: "is_derived", label: "是否派生参考", type: "select", options: booleanOptions },
    { key: "md5checksum", label: "MD5 校验值", type: "text", placeholder: "32 位十六进制（建议）" },
    { key: "source_uri", label: "来源 URI", type: "text", placeholder: "https://..." },
    { key: "species_ontology_term", label: "物种本体 Term", type: "text", placeholder: "Zea mays" },
    { key: "species_ontology_termuri", label: "物种本体 URI", type: "text", placeholder: "https://..." },
    {
      key: "source_germplasm_id",
      label: "来源 Germplasm",
      type: "select",
      options: optionOrNone("不关联 Germplasm", germplasmOptions),
    },
  ], [germplasmOptions]);

  const renderFormExtra = useCallback((props: { formData: Record<string, unknown> }) => {
    const md5Warning = warnMd5Checksum(props.formData.md5checksum);
    return (
      <div className="col-span-2 space-y-2 rounded-lg border border-indigo-100 bg-indigo-50/60 p-3 text-xs text-indigo-900 dark:border-indigo-900/40 dark:bg-indigo-950/30 dark:text-indigo-100">
        <p className="font-medium">校验说明</p>
        <p>删除前服务端会检查是否仍被 Reference / VariantSet / Variant 引用。来源 Germplasm 必须已存在。</p>
        {md5Warning ? <p className="text-amber-700 dark:text-amber-300">{md5Warning}</p> : null}
      </div>
    );
  }, []);

  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">
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">ReferenceSet 名称</Label>
          <Input
            value={draftQuery.reference_set_name ?? ""}
            onChange={(event) => setDraftQuery((current) => ({ ...current, reference_set_name: event.target.value }))}
            placeholder="名称模糊匹配"
          />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">Assembly PUI</Label>
          <Input
            value={draftQuery.assembly_pui ?? ""}
            onChange={(event) => setDraftQuery((current) => ({ ...current, assembly_pui: event.target.value }))}
            placeholder="PUI 模糊匹配"
          />
        </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>
  ), [draftQuery]);

  return (
    <BrapiEntityPage
      useEnhancedDialog
      icon={Layers}
      iconBg="bg-gradient-to-br from-indigo-500 to-violet-600"
      title="ReferenceSet 参考基因组集合"
      description="维护参考基因组集合、Assembly 标识、物种信息与来源 Germplasm。点击进入详情可管理下属 Reference。"
      addLabel="新增 ReferenceSet"
      columns={[
        {
          key: "reference_set_name",
          label: "名称",
          render: (value, row) => {
            const id = String(row.id ?? row.referenceSetDbId ?? "");
            const name = String(value ?? "—");
            if (!id) return name;
            return (
              <Link href={`/genotyping/reference-set/referencesets/${encodeURIComponent(id)}`} className="font-medium text-indigo-600 hover:underline dark:text-indigo-400">
                {name}
              </Link>
            );
          },
        },
        { key: "assembly_pui", label: "Assembly PUI" },
        { key: "species_ontology_term", label: "物种" },
        { key: "source_germplasm_name", label: "来源 Germplasm" },
        { key: "reference_count", label: "Reference 数" },
        { key: "variantset_count", label: "VariantSet 数" },
        { key: "variant_count", label: "Variant 数" },
        { key: "is_derived", label: "派生", render: boolLabel },
      ]}
      fields={fields}
      data={[]}
      stats={[{
        label: "/brapi/v2/referencesets",
        value: "BrAPI",
        className: "bg-indigo-50 text-indigo-700 dark:bg-indigo-400/10 dark:text-indigo-200",
      }]}
      loadData={loadRows}
      fetchRecord={fetchRecord}
      createRecord={(payload) => createReferenceSetRow(payload) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updateReferenceSetRow(id, payload) as unknown as Promise<Record<string, unknown>>}
      deleteRecord={deleteReferenceSetRow}
      renderQueryForm={() => renderQueryForm()}
      renderFormExtra={renderFormExtra}
    />
  );
}
