"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import { Dna, RotateCcw, Search } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { loadAlleleCallRows, loadCallSetPageData } from "../api";
import { NONE_SELECT_VALUE, type AlleleCallQuery, type AlleleCallRecord, type SelectOption } from "../types";

const emptyQuery = (): AlleleCallQuery => ({
  call_set_id: NONE_SELECT_VALUE,
  variant_id: NONE_SELECT_VALUE,
  variant_set_id: NONE_SELECT_VALUE,
});

export function AlleleCallTab() {
  const searchParams = useSearchParams();
  const [callSetOptions, setCallSetOptions] = useState<SelectOption[]>([]);
  const [variantSetOptions, setVariantSetOptions] = useState<SelectOption[]>([]);
  const [draftQuery, setDraftQuery] = useState<AlleleCallQuery>(() => ({
    ...emptyQuery(),
    variant_id: searchParams.get("variant_id") || NONE_SELECT_VALUE,
  }));
  const [appliedQuery, setAppliedQuery] = useState<AlleleCallQuery>(() => ({
    ...emptyQuery(),
    variant_id: searchParams.get("variant_id") || NONE_SELECT_VALUE,
  }));
  const [rows, setRows] = useState<AlleleCallRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let mounted = true;
    loadCallSetPageData()
      .then(({ options, rows: callSetRows }) => {
        if (!mounted) return;
        setCallSetOptions(callSetRows.map((item) => ({
          value: String(item.id ?? item.callSetDbId ?? ""),
          label: String(item.call_set_name ?? item.callSetName ?? item.id ?? ""),
        })).filter((item) => item.value));
        setVariantSetOptions(options.variantSets);
      })
      .catch(() => {
        if (!mounted) return;
      });
    return () => { mounted = false; };
  }, []);

  const loadRows = useCallback(async () => {
    return loadAlleleCallRows(appliedQuery);
  }, [appliedQuery]);

  useEffect(() => {
    let mounted = true;
    setLoading(true);
    setError(null);
    loadRows()
      .then((data) => {
        if (!mounted) return;
        setRows(data);
      })
      .catch((event) => {
        if (!mounted) return;
        setError(event instanceof Error ? event.message : "加载 allele_call 失败");
      })
      .finally(() => {
        if (mounted) setLoading(false);
      });
    return () => { mounted = false; };
  }, [loadRows]);

  const hint = useMemo(() => {
    if (appliedQuery.variant_id && appliedQuery.variant_id !== NONE_SELECT_VALUE) {
      return "按 Variant 过滤查看该位点下的 genotype 调用结果。";
    }
    return "allele_call 通常通过 VCF/HapMap/矩阵导入；导入时会自动绑定 callset 与 variantset 关系。";
  }, [appliedQuery.variant_id]);

  return (
    <div className="space-y-4">
      <div className="rounded-xl border border-slate-200 bg-white p-4 dark:border-slate-800 dark:bg-slate-950">
        <div className="mb-3 flex items-center gap-2">
          <Dna className="h-4 w-4 text-emerald-500" />
          <div>
            <h2 className="text-base font-semibold">allele_call 调用结果</h2>
            <p className="text-xs text-slate-500">{hint}</p>
          </div>
        </div>
        <div className="grid gap-3 md:grid-cols-3">
          <div className="space-y-1.5">
            <Label className="text-xs text-slate-500">CallSet</Label>
            <Select
              value={draftQuery.call_set_id ?? NONE_SELECT_VALUE}
              onValueChange={(value) => setDraftQuery((current) => ({ ...current, call_set_id: value }))}
            >
              <SelectTrigger><SelectValue placeholder="全部" /></SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE_SELECT_VALUE}>全部</SelectItem>
                {callSetOptions.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>
        <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>

      {error ? (
        <div className="rounded-xl border border-destructive/20 bg-destructive/10 px-4 py-3 text-sm text-destructive">
          {error}
        </div>
      ) : null}

      <div className="rounded-xl border border-slate-200 bg-white dark:border-slate-800 dark:bg-slate-950">
        {loading ? (
          <div className="p-4"><Skeleton className="h-64 w-full" /></div>
        ) : rows.length === 0 ? (
          <p className="p-6 text-sm text-slate-500">暂无 allele_call 记录。</p>
        ) : (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>CallSet</TableHead>
                <TableHead>Variant</TableHead>
                <TableHead>VariantSet</TableHead>
                <TableHead>Genotype</TableHead>
                <TableHead>Read Depth</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {rows.map((row) => (
                <TableRow key={String(row.id || `${row.call_set_id}-${row.variant_id}`)}>
                  <TableCell>{row.call_set_name || row.call_set_id || "—"}</TableCell>
                  <TableCell>{row.variant_name || row.variant_id || "—"}</TableCell>
                  <TableCell>
                    <Badge variant="outline">{row.variant_set_id || "—"}</Badge>
                  </TableCell>
                  <TableCell>{row.genotype || "—"}</TableCell>
                  <TableCell>{row.read_depth ?? "—"}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        )}
      </div>
    </div>
  );
}
