"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { ArrowLeft, Binary, FileDown, FlaskConical, Layers, 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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { VariantSetAnalysisPanel } from "../../components/VariantSetAnalysisPanel";
import { VariantSetFormatPanel } from "../../components/VariantSetFormatPanel";
import {
  fetchVariantSetCallsets,
  fetchVariantSetDetail,
  fetchVariantSetVariants,
} from "../../api";

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

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [detail, setDetail] = useState<Awaited<ReturnType<typeof fetchVariantSetDetail>> | null>(null);
  const [variants, setVariants] = useState<Array<Record<string, unknown>>>([]);
  const [callsets, setCallsets] = useState<Array<Record<string, unknown>>>([]);

  const loadDetail = useCallback(async () => {
    const [variantSet, variantRows, callsetRows] = await Promise.all([
      fetchVariantSetDetail(variantSetDbId),
      fetchVariantSetVariants(variantSetDbId),
      fetchVariantSetCallsets(variantSetDbId),
    ]);
    setDetail(variantSet);
    setVariants(variantRows);
    setCallsets(callsetRows);
  }, [variantSetDbId]);

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

  if (loading) {
    return (
      <div className="space-y-4 p-1">
        <Skeleton className="h-10 w-48" />
        <Skeleton className="h-36 w-full" />
        <Skeleton className="h-96 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 || "VariantSet 不存在"}
        <div className="mt-4">
          <Button asChild variant="outline">
            <Link href="/genotyping/variant-set"><ArrowLeft className="mr-2 h-4 w-4" />返回列表</Link>
          </Button>
        </div>
      </div>
    );
  }

  const hasDependencies = (detail.variant_count ?? 0) > 0
    || (detail.callset_count ?? 0) > 0
    || (detail.analysis_count ?? 0) > 0
    || (detail.format_count ?? 0) > 0;

  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-set"><ArrowLeft className="mr-2 h-4 w-4" />返回 VariantSet 列表</Link>
        </Button>
        {hasDependencies ? (
          <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">
            删除前请确认无 Variant、CallSet、Analysis 或 Format 引用
          </Badge>
        ) : null}
      </div>

      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2 text-lg">
            <Layers className="h-5 w-5 text-violet-500" />
            {detail.variant_set_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">VariantSet ID：</span>{detail.id}</div>
          <div><span className="text-slate-500">ReferenceSet：</span>{detail.reference_set_name || "N/A"}</div>
          <div><span className="text-slate-500">Study：</span>{detail.study_name || "N/A"}</div>
          <div><span className="text-slate-500">Variant 数：</span>{detail.variant_count ?? 0}</div>
          <div><span className="text-slate-500">CallSet 数：</span>{detail.callset_count ?? 0}</div>
          <div><span className="text-slate-500">Analysis 数：</span>{detail.analysis_count ?? 0}</div>
          <div><span className="text-slate-500">Formats 数：</span>{detail.format_count ?? 0}</div>
        </CardContent>
      </Card>

      <Tabs defaultValue="overview" className="space-y-4">
        <TabsList className="w-full justify-start overflow-x-auto rounded-lg border bg-white p-1 dark:border-slate-800 dark:bg-slate-950 sm:w-fit">
          <TabsTrigger value="overview" className="gap-2">
            <Sigma className="h-4 w-4" />
            概览
          </TabsTrigger>
          <TabsTrigger value="analysis" className="gap-2">
            <FlaskConical className="h-4 w-4" />
            Analysis
          </TabsTrigger>
          <TabsTrigger value="formats" className="gap-2">
            <FileDown className="h-4 w-4" />
            Formats
          </TabsTrigger>
        </TabsList>

        <TabsContent value="overview" className="space-y-4">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-base">
                <Sigma className="h-4 w-4 text-rose-500" />
                Variants
              </CardTitle>
            </CardHeader>
            <CardContent>
              {variants.length === 0 ? (
                <p className="text-sm text-slate-500">暂无 Variant 位点。</p>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Variant ID</TableHead>
                      <TableHead>名称</TableHead>
                      <TableHead>类型</TableHead>
                      <TableHead>起点</TableHead>
                      <TableHead>终点</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {variants.slice(0, 20).map((row) => {
                      const id = String(row.variantDbId ?? row.id ?? "");
                      const names = Array.isArray(row.variantNames) ? row.variantNames.join(", ") : String(row.variantName ?? "—");
                      return (
                        <TableRow key={id}>
                          <TableCell>
                            {id ? (
                              <Link href={`/genotyping/variant/variants/${encodeURIComponent(id)}`} className="text-rose-600 hover:underline dark:text-rose-400">
                                {id}
                              </Link>
                            ) : "—"}
                          </TableCell>
                          <TableCell>{names}</TableCell>
                          <TableCell>{String(row.variantType ?? "—")}</TableCell>
                          <TableCell>{String(row.start ?? "—")}</TableCell>
                          <TableCell>{String(row.end ?? "—")}</TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              )}
              {variants.length > 20 ? (
                <p className="mt-2 text-xs text-slate-500">仅展示前 20 条，完整列表请前往 Variant 管理页筛选。</p>
              ) : null}
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-base">
                <Binary className="h-4 w-4 text-sky-500" />
                CallSets
              </CardTitle>
            </CardHeader>
            <CardContent>
              {callsets.length === 0 ? (
                <p className="text-sm text-slate-500">暂无 CallSet。</p>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>CallSet ID</TableHead>
                      <TableHead>名称</TableHead>
                      <TableHead>Sample</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {callsets.map((row) => (
                      <TableRow key={String(row.callSetDbId ?? row.id ?? Math.random())}>
                        <TableCell>{String(row.callSetDbId ?? "—")}</TableCell>
                        <TableCell>{String(row.callSetName ?? "—")}</TableCell>
                        <TableCell>{String(row.sampleName ?? row.sampleDbId ?? "—")}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="analysis">
          <VariantSetAnalysisPanel variantSetDbId={variantSetDbId} onChanged={loadDetail} />
        </TabsContent>

        <TabsContent value="formats">
          <VariantSetFormatPanel variantSetDbId={variantSetDbId} onChanged={loadDetail} />
        </TabsContent>
      </Tabs>
    </div>
  );
}
