"use client";

import Link from "next/link";
import { useCallback, useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import { RotateCcw, Search, Sigma } 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 {
  createVariantRow,
  deleteVariantRow,
  fetchVariantDetail,
  loadVariantPageData,
  normalizeVariantFormData,
  updateVariantRow,
} from "../api";
import { NONE_SELECT_VALUE, type SelectOption, type VariantQuery } from "../types";

const variantTypeOptions: SelectOption[] = [
  { value: NONE_SELECT_VALUE, label: "不指定类型" },
  { value: "SNP", label: "SNP / 单核苷酸变异" },
  { value: "INDEL", label: "INDEL / 插入缺失" },
  { value: "SV", label: "SV / 结构变异" },
  { value: "CNV", label: "CNV / 拷贝数变异" },
];

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

const emptyQuery = (): VariantQuery => ({
  variant_name: "",
  variant_type: NONE_SELECT_VALUE,
  variant_set_id: NONE_SELECT_VALUE,
  reference_set_id: NONE_SELECT_VALUE,
});

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

const optionLabel = (options: SelectOption[], value: unknown) => {
  const text = String(value ?? "").trim();
  return options.find((option) => option.value === text)?.label || text || "N/A";
};

const boolLabel = (value: unknown) => {
  if (value === true) return "是";
  if (value === false) return "否";
  return "N/A";
};

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

export function VariantTab() {
  const searchParams = useSearchParams();
  const [referenceSetOptions, setReferenceSetOptions] = useState<SelectOption[]>([]);
  const [variantSetOptions, setVariantSetOptions] = useState<SelectOption[]>([]);
  const [draftQuery, setDraftQuery] = useState<VariantQuery>(() => ({
    ...emptyQuery(),
    variant_set_id: toSelectValue(searchParams.get("variantSetDbId")),
  }));
  const [appliedQuery, setAppliedQuery] = useState<VariantQuery>(() => ({
    ...emptyQuery(),
    variant_set_id: toSelectValue(searchParams.get("variantSetDbId")),
  }));

  const loadRows = useCallback(async () => {
    const { options, rows } = await loadVariantPageData({ query: appliedQuery });
    setReferenceSetOptions(options.referenceSets);
    setVariantSetOptions(options.variantSets);
    return rows as unknown as Record<string, unknown>[];
  }, [appliedQuery]);

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

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "id", label: "Variant ID", type: "text", required: true, placeholder: "variant-001" },
    { key: "variant_name", label: "变异名称", type: "text", required: true, placeholder: "S1_12345_A_T" },
    { key: "variant_type", label: "变异类型", type: "select", options: variantTypeOptions },
    {
      key: "variant_set_id",
      label: "VariantSet",
      type: "select",
      options: optionOrNone("不关联 VariantSet", variantSetOptions),
    },
    {
      key: "reference_set_id",
      label: "ReferenceSet",
      type: "select",
      options: optionOrNone("不关联 ReferenceSet", referenceSetOptions),
    },
    { key: "start", label: "起点", type: "number", placeholder: "1000" },
    { key: "end", label: "终点", type: "number", placeholder: "1001" },
    { key: "reference_bases", label: "参考碱基", type: "text", placeholder: "A" },
    { key: "svlen", label: "SV 长度", type: "number", placeholder: "1" },
    { key: "filters_applied", label: "已应用过滤", type: "select", options: booleanOptions },
    { key: "filters_passed", label: "通过过滤", type: "select", options: booleanOptions },
  ], [referenceSetOptions, variantSetOptions]);

  const renderFormExtra = useCallback(() => (
    <div className="col-span-2 rounded-lg border border-rose-100 bg-rose-50/60 p-3 text-xs text-rose-900 dark:border-rose-900/40 dark:bg-rose-950/30 dark:text-rose-100">
      <p className="font-medium">位点定义说明</p>
      <p className="mt-1 text-rose-800/80 dark:text-rose-200/80">
        Variant 仅描述位点坐标与参考碱基，样本 genotype 结果写入 allele_call。大批量位点建议通过文件导入。
      </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 xl:grid-cols-5">
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">变异名称</Label>
          <Input
            value={draftQuery.variant_name ?? ""}
            onChange={(event) => setDraftQuery((current) => ({ ...current, variant_name: event.target.value }))}
            placeholder="variantName 模糊匹配"
          />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">变异类型</Label>
          <Select
            value={draftQuery.variant_type ?? NONE_SELECT_VALUE}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, variant_type: value }))}
          >
            <SelectTrigger><SelectValue placeholder="全部" /></SelectTrigger>
            <SelectContent>
              <SelectItem value={NONE_SELECT_VALUE}>全部</SelectItem>
              {variantTypeOptions.filter((item) => item.value !== NONE_SELECT_VALUE).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">VariantSet</Label>
          <Select
            value={draftQuery.variant_set_id ?? NONE_SELECT_VALUE}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, variant_set_id: value }))}
          >
            <SelectTrigger><SelectValue placeholder="全部" /></SelectTrigger>
            <SelectContent>
              <SelectItem value={NONE_SELECT_VALUE}>全部</SelectItem>
              {variantSetOptions.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">ReferenceSet</Label>
          <Select
            value={draftQuery.reference_set_id ?? NONE_SELECT_VALUE}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, reference_set_id: value }))}
          >
            <SelectTrigger><SelectValue placeholder="全部" /></SelectTrigger>
            <SelectContent>
              <SelectItem value={NONE_SELECT_VALUE}>全部</SelectItem>
              {referenceSetOptions.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, referenceSetOptions, variantSetOptions]);

  return (
    <BrapiEntityPage
      useEnhancedDialog
      icon={Sigma}
      iconBg="bg-gradient-to-br from-rose-600 to-pink-700"
      title="Variant 变异位点"
      description="维护变异集合中的 SNP、INDEL、SV 等位点和坐标信息。"
      addLabel="新增 Variant"
      columns={[
        {
          key: "variant_name",
          label: "变异名称",
          render: (value, row) => {
            const id = String(row.id ?? row.variantDbId ?? "");
            const name = String(value ?? "—");
            if (!id) return name;
            return (
              <Link
                href={`/genotyping/variant/variants/${encodeURIComponent(id)}`}
                className="font-medium text-rose-600 hover:underline dark:text-rose-400"
              >
                {name}
              </Link>
            );
          },
        },
        { key: "variant_type", label: "类型", render: (value) => optionLabel(variantTypeOptions, value) },
        { key: "variant_set_name", label: "VariantSet" },
        { key: "reference_set_name", label: "ReferenceSet" },
        { key: "start", label: "起点" },
        { key: "end", label: "终点" },
        { key: "reference_bases", label: "参考碱基" },
        { key: "filters_passed", label: "过滤", render: boolLabel },
      ]}
      fields={fields}
      data={[]}
      stats={[{ label: "/brapi/v2/variants", value: "BrAPI", className: "bg-rose-50 text-rose-700 dark:bg-rose-400/10 dark:text-rose-200" }]}
      loadData={loadRows}
      fetchRecord={fetchRecord}
      createRecord={(payload) => createVariantRow(payload) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updateVariantRow(id, payload) as unknown as Promise<Record<string, unknown>>}
      deleteRecord={deleteVariantRow}
      renderQueryForm={() => renderQueryForm()}
      renderFormExtra={renderFormExtra}
    />
  );
}
