"use client";

import Link from "next/link";
import { useCallback, useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import { BookOpen, 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 {
  createReferenceRow,
  deleteReferenceRow,
  fetchReferenceDetail,
  loadReferenceSetPageData,
  normalizeReferenceFormData,
  updateReferenceRow,
} from "../api";
import { NONE_SELECT_VALUE, type ReferenceQuery, type SelectOption } from "../types";

const emptyQuery = (): ReferenceQuery => ({
  reference_name: "",
  reference_set_id: NONE_SELECT_VALUE,
});

function toSelectValue(value: string | null | undefined) {
  return value && value !== NONE_SELECT_VALUE ? value : NONE_SELECT_VALUE;
}

export function ReferenceTab() {
  const searchParams = useSearchParams();
  const [referenceSetOptions, setReferenceSetOptions] = useState<SelectOption[]>([]);
  const [draftQuery, setDraftQuery] = useState<ReferenceQuery>(() => ({
    ...emptyQuery(),
    reference_set_id: searchParams.get("reference_set_id") ?? NONE_SELECT_VALUE,
  }));
  const [appliedQuery, setAppliedQuery] = useState<ReferenceQuery>(() => ({
    ...emptyQuery(),
    reference_set_id: searchParams.get("reference_set_id") ?? NONE_SELECT_VALUE,
  }));

  const urlDefaultFormValues = useMemo(() => {
    const referenceSetId = searchParams.get("reference_set_id");
    return referenceSetId ? { reference_set_id: referenceSetId } : undefined;
  }, [searchParams]);

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

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

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "id", label: "Reference ID", type: "text", placeholder: "留空则系统自动生成（导入时可指定）" },
    { key: "reference_name", label: "参考序列名称", type: "text", required: true, placeholder: "如 chr1" },
    {
      key: "reference_set_id",
      label: "ReferenceSet",
      type: "select",
      required: true,
      options: referenceSetOptions,
    },
    { key: "length", label: "序列长度", type: "number", placeholder: "非负整数" },
    { key: "source_divergence", label: "来源差异度", type: "number", placeholder: "0.01" },
    { key: "md5checksum", label: "MD5", type: "text", placeholder: "md5 checksum", colSpan: 2 },
  ], [referenceSetOptions]);

  const renderFormExtra = useCallback(() => (
    <div className="col-span-2 rounded-lg border border-emerald-100 bg-emerald-50/60 p-3 text-xs text-emerald-900 dark:border-emerald-900/40 dark:bg-emerald-950/30 dark:text-emerald-100">
      <p className="font-medium">校验说明</p>
      <p>ReferenceSet 必选且必须存在。删除前服务端会检查 ReferenceBases 引用。详情页可维护序列分页。</p>
    </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">Reference 名称</Label>
          <Input
            value={draftQuery.reference_name ?? ""}
            onChange={(event) => setDraftQuery((current) => ({ ...current, reference_name: event.target.value }))}
            placeholder="名称模糊匹配"
          />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">ReferenceSet</Label>
          <Select
            value={toSelectValue(draftQuery.reference_set_id)}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, reference_set_id: value }))}
          >
            <SelectTrigger><SelectValue placeholder="全部" /></SelectTrigger>
            <SelectContent>
              <SelectItem value={NONE_SELECT_VALUE}>全部 ReferenceSet</SelectItem>
              {referenceSetOptions.map((option) => (
                <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </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, referenceSetOptions]);

  return (
    <BrapiEntityPage
      useEnhancedDialog
      icon={BookOpen}
      iconBg="bg-gradient-to-br from-emerald-500 to-teal-600"
      title="Reference 参考序列"
      description="维护染色体、Contig 或 Scaffold 等参考序列，隶属于 ReferenceSet。"
      addLabel="新增 Reference"
      defaultFormValues={urlDefaultFormValues}
      columns={[
        {
          key: "reference_name",
          label: "序列名称",
          render: (value, row) => {
            const id = String(row.id ?? row.referenceDbId ?? "");
            const name = String(value ?? "—");
            if (!id) return name;
            return (
              <Link href={`/genotyping/reference-set/references/${encodeURIComponent(id)}`} className="font-medium text-emerald-600 hover:underline dark:text-emerald-400">
                {name}
              </Link>
            );
          },
        },
        { key: "reference_set_name", label: "ReferenceSet" },
        { key: "length", label: "长度" },
        { key: "bases_page_count", label: "Bases 分页数" },
        { key: "bases_total_length", label: "Bases 总长度" },
        { key: "source_divergence", label: "来源差异" },
        { key: "md5checksum", label: "MD5" },
      ]}
      fields={fields}
      data={[]}
      stats={[{
        label: "/brapi/v2/references",
        value: "BrAPI",
        className: "bg-emerald-50 text-emerald-700 dark:bg-emerald-400/10 dark:text-emerald-200",
      }]}
      loadData={loadRows}
      fetchRecord={fetchRecord}
      createRecord={(payload) => createReferenceRow(payload) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updateReferenceRow(id, payload) as unknown as Promise<Record<string, unknown>>}
      deleteRecord={deleteReferenceRow}
      renderQueryForm={() => renderQueryForm()}
      renderFormExtra={renderFormExtra}
    />
  );
}
