"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 { 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 {
  createVariantSetRow,
  deleteVariantSetRow,
  fetchVariantSetDetail,
  loadVariantSetPageData,
  normalizeVariantSetFormData,
  updateVariantSetRow,
} from "../api";
import { NONE_SELECT_VALUE, type SelectOption, type VariantSetQuery } from "../types";

const emptyQuery = (): VariantSetQuery => ({
  variant_set_name: "",
  reference_set_id: NONE_SELECT_VALUE,
  study_id: NONE_SELECT_VALUE,
});

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

export function VariantSetTab() {
  const [referenceSetOptions, setReferenceSetOptions] = useState<SelectOption[]>([]);
  const [studyOptions, setStudyOptions] = useState<SelectOption[]>([]);
  const [draftQuery, setDraftQuery] = useState<VariantSetQuery>(emptyQuery);
  const [appliedQuery, setAppliedQuery] = useState<VariantSetQuery>(emptyQuery);

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

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

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "id", label: "VariantSet ID", type: "text", required: true, placeholder: "variantset-001" },
    {
      key: "variant_set_name",
      label: "变异集合名称",
      type: "text",
      required: true,
      placeholder: "如 Hapmap 2026",
    },
    {
      key: "reference_set_id",
      label: "ReferenceSet",
      type: "select",
      options: optionOrNone("不关联 ReferenceSet", referenceSetOptions),
    },
    {
      key: "study_id",
      label: "Study",
      type: "select",
      options: optionOrNone("不关联 Study", studyOptions),
    },
  ], [referenceSetOptions, studyOptions]);

  const renderFormExtra = useCallback(() => (
    <div className="col-span-2 rounded-lg border border-violet-100 bg-violet-50/60 p-3 text-xs text-violet-900 dark:border-violet-900/40 dark:bg-violet-950/30 dark:text-violet-100">
      <p className="font-medium">ReferenceSet 一致性</p>
      <p className="mt-1 text-violet-800/80 dark:text-violet-200/80">
        建议为 VariantSet 指定 ReferenceSet；下属 Variant 的 reference_set_id 应与此处保持一致。
      </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-4">
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">变异集合名称</Label>
          <Input
            value={draftQuery.variant_set_name ?? ""}
            onChange={(event) => setDraftQuery((current) => ({ ...current, variant_set_name: event.target.value }))}
            placeholder="variantSetName 模糊匹配"
          />
        </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 className="space-y-1.5">
          <Label className="text-xs text-slate-500">Study</Label>
          <Select
            value={draftQuery.study_id ?? NONE_SELECT_VALUE}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, study_id: value }))}
          >
            <SelectTrigger><SelectValue placeholder="全部" /></SelectTrigger>
            <SelectContent>
              <SelectItem value={NONE_SELECT_VALUE}>全部</SelectItem>
              {studyOptions.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, studyOptions]);

  return (
    <BrapiEntityPage
      useEnhancedDialog
      icon={Layers}
      iconBg="bg-gradient-to-br from-violet-500 to-purple-600"
      title="VariantSet 变异集合"
      description="维护测序、芯片或 Study 下的变异位点集合，并关联 ReferenceSet 与 Study。"
      addLabel="新增 VariantSet"
      columns={[
        {
          key: "variant_set_name",
          label: "名称",
          render: (value, row) => {
            const id = String(row.id ?? row.variantSetDbId ?? "");
            const name = String(value ?? "—");
            if (!id) return name;
            return (
              <Link
                href={`/genotyping/variant-set/variant-sets/${encodeURIComponent(id)}`}
                className="font-medium text-violet-600 hover:underline dark:text-violet-400"
              >
                {name}
              </Link>
            );
          },
        },
        { key: "reference_set_name", label: "ReferenceSet" },
        { key: "study_name", label: "Study" },
        {
          key: "variant_count",
          label: "Variant 数",
          render: (value) => <Badge variant="outline">{Number(value ?? 0)}</Badge>,
        },
        {
          key: "callset_count",
          label: "CallSet 数",
          render: (value) => <Badge variant="outline">{Number(value ?? 0)}</Badge>,
        },
        { key: "analysis_count", label: "Analysis 数" },
        { key: "format_count", label: "Formats 数" },
      ]}
      fields={fields}
      data={[]}
      stats={[{
        label: "/brapi/v2/variantsets",
        value: "BrAPI",
        className: "bg-violet-50 text-violet-700 dark:bg-violet-400/10 dark:text-violet-200",
      }]}
      loadData={loadRows}
      fetchRecord={fetchRecord}
      createRecord={(payload) => createVariantSetRow(payload) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updateVariantSetRow(id, payload) as unknown as Promise<Record<string, unknown>>}
      deleteRecord={deleteVariantSetRow}
      renderQueryForm={renderQueryForm}
      renderFormExtra={renderFormExtra}
    />
  );
}
