"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { ArrowLeft, Sigma } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { fetchVariantDetail } from "../../api";
import { VariantMarkerPositionCard } from "../../components/VariantMarkerPositionCard";

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

export default function VariantDetailPage() {
  const params = useParams<{ variantDbId: string }>();
  const variantDbId = decodeURIComponent(params.variantDbId);

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [detail, setDetail] = useState<Awaited<ReturnType<typeof fetchVariantDetail>> | null>(null);

  useEffect(() => {
    let mounted = true;
    setLoading(true);
    setError(null);
    fetchVariantDetail(variantDbId)
      .then((result) => {
        if (!mounted) return;
        setDetail(result);
      })
      .catch((event) => {
        if (!mounted) return;
        setError(event instanceof Error ? event.message : "加载 Variant 详情失败");
      })
      .finally(() => {
        if (mounted) setLoading(false);
      });
    return () => { mounted = false; };
  }, [variantDbId]);

  if (loading) {
    return (
      <div className="space-y-4 p-1">
        <Skeleton className="h-10 w-48" />
        <Skeleton className="h-36 w-full" />
      </div>
    );
  }

  if (error || !detail) {
    return (
      <div className="rounded-xl border border-destructive/20 bg-destructive/10 px-4 py-6 text-sm text-destructive">
        {error || "Variant 不存在"}
        <div className="mt-4">
          <Button asChild variant="outline">
            <Link href="/genotyping/variant"><ArrowLeft className="mr-2 h-4 w-4" />返回列表</Link>
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="flex min-h-full flex-col gap-4">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <Button asChild variant="outline" size="sm">
          <Link href="/genotyping/variant"><ArrowLeft className="mr-2 h-4 w-4" />返回 Variant 列表</Link>
        </Button>
        {(detail.allele_call_count ?? 0) > 0 ? (
          <Badge variant="outline" className="border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-200">
            已有 {detail.allele_call_count} 条 allele_call，删除前请先处理关联数据
          </Badge>
        ) : null}
      </div>

      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2 text-lg">
            <Sigma className="h-5 w-5 text-rose-500" />
            {detail.variant_name || detail.id}
          </CardTitle>
        </CardHeader>
        <CardContent className="grid gap-3 text-sm sm:grid-cols-2 lg:grid-cols-4">
          <div><span className="text-slate-500">Variant ID：</span>{detail.id}</div>
          <div><span className="text-slate-500">类型：</span>{detail.variant_type || "N/A"}</div>
          <div><span className="text-slate-500">VariantSet：</span>{detail.variant_set_name || "N/A"}</div>
          <div><span className="text-slate-500">ReferenceSet：</span>{detail.reference_set_name || "N/A"}</div>
          <div><span className="text-slate-500">起点：</span>{detail.start ?? "N/A"}</div>
          <div><span className="text-slate-500">终点：</span>{detail.end ?? "N/A"}</div>
          <div><span className="text-slate-500">参考碱基：</span>{detail.reference_bases || "N/A"}</div>
          <div><span className="text-slate-500">SV 长度：</span>{detail.svlen ?? "N/A"}</div>
          <div><span className="text-slate-500">已应用过滤：</span>{boolLabel(detail.filters_applied)}</div>
          <div><span className="text-slate-500">通过过滤：</span>{boolLabel(detail.filters_passed)}</div>
          <div><span className="text-slate-500">allele_call 数：</span>{detail.allele_call_count ?? 0}</div>
          {(detail.allele_call_count ?? 0) > 0 ? (
            <div className="sm:col-span-2">
              <Button asChild variant="link" className="h-auto px-0 text-cyan-600 dark:text-cyan-400">
                <Link href={`/genotyping/call-set?tab=allele-calls&variant_id=${encodeURIComponent(detail.id)}`}>
                  查看该位点下的 allele_call
                </Link>
              </Button>
            </div>
          ) : null}
        </CardContent>
      </Card>

      <VariantMarkerPositionCard variantDbId={detail.id} />
    </div>
  );
}
