"use client";

import Link from "next/link";
import { Suspense, useCallback, useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { ArrowLeft, GitBranch, Share2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { CrossPedigreeProvider } from "../../CrossPedigreeContext";
import { fetchPedigreeNodeByGermplasm } from "../../api";
import { PedigreeEdgePanel } from "../../components/PedigreeEdgePanel";
import { PedigreeNodeFormPanel } from "../../components/PedigreeNodeFormPanel";
import type { PedigreeRecord } from "../../types";

function PedigreeNodeDetailContent() {
  const params = useParams<{ germplasmDbId: string }>();
  const germplasmDbId = decodeURIComponent(params.germplasmDbId);

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [node, setNode] = useState<PedigreeRecord | null>(null);
  const [refreshKey, setRefreshKey] = useState(0);

  const loadDetail = useCallback(async () => {
    const record = await fetchPedigreeNodeByGermplasm(germplasmDbId);
    setNode(record);
  }, [germplasmDbId]);

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

  const bumpRefresh = () => setRefreshKey((value) => value + 1);

  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) {
    return (
      <div className="rounded-xl border border-destructive/20 bg-destructive/10 px-4 py-6 text-sm text-destructive">
        {error}
        <div className="mt-4">
          <Button asChild variant="outline">
            <Link href="/germplasm/cross-pedigree?tab=pedigree-nodes">
              <ArrowLeft className="mr-2 h-4 w-4" />返回 Pedigree 列表
            </Link>
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="flex min-h-full flex-col gap-4">
      <div className="flex flex-wrap gap-2">
        <Button asChild variant="outline" size="sm">
          <Link href="/germplasm/cross-pedigree?tab=pedigree-nodes">
            <ArrowLeft className="mr-2 h-4 w-4" />返回 Pedigree Node 列表
          </Link>
        </Button>
        <Button asChild variant="outline" size="sm">
          <Link href={`/germplasm/germplasm/${encodeURIComponent(germplasmDbId)}?tab=pedigree`}>
            <Share2 className="mr-2 h-4 w-4" />种质详情 Pedigree Tab
          </Link>
        </Button>
      </div>

      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2 text-lg">
            <Share2 className="h-5 w-5 text-sky-500" />
            {node?.germplasm_name || germplasmDbId}
          </CardTitle>
        </CardHeader>
        <CardContent className="grid gap-3 text-sm sm:grid-cols-2 lg:grid-cols-3">
          <div><span className="text-slate-500">Germplasm ID：</span>{germplasmDbId}</div>
          <div><span className="text-slate-500">杂交项目：</span>{node?.crossing_project_name || "—"}</div>
          <div><span className="text-slate-500">杂交年份：</span>{node?.crossing_year ?? "—"}</div>
          <div><span className="text-slate-500">家系编号：</span>{node?.family_code || "—"}</div>
          <div className="sm:col-span-2"><span className="text-slate-500">系谱字符串：</span>{node?.pedigree_string || "—"}</div>
          <div><span className="text-slate-500">亲本数：</span>{node?.parents?.length ?? 0}</div>
          <div><span className="text-slate-500">同胞数：</span>{node?.siblings?.length ?? 0}</div>
        </CardContent>
      </Card>

      <Tabs defaultValue="node" 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="node" className="gap-2">
            <Share2 className="h-4 w-4" />
            节点信息
          </TabsTrigger>
          <TabsTrigger value="edges" className="gap-2">
            <GitBranch className="h-4 w-4" />
            系谱边
          </TabsTrigger>
        </TabsList>

        <TabsContent value="node">
          <PedigreeNodeFormPanel
            key={`node-${refreshKey}`}
            scopeGermplasmDbId={germplasmDbId}
            scopeGermplasmName={node?.germplasm_name}
            onChanged={() => {
              bumpRefresh();
              loadDetail().catch(() => undefined);
            }}
          />
        </TabsContent>

        <TabsContent value="edges">
          <PedigreeEdgePanel
            key={`edge-${refreshKey}`}
            scopeGermplasmDbId={germplasmDbId}
            onChanged={bumpRefresh}
          />
        </TabsContent>
      </Tabs>
    </div>
  );
}

export default function PedigreeNodeDetailPage() {
  return (
    <Suspense fallback={<Skeleton className="h-96 w-full rounded-xl" />}>
      <CrossPedigreeProvider>
        <PedigreeNodeDetailContent />
      </CrossPedigreeProvider>
    </Suspense>
  );
}
