"use client";

import Link from "next/link";
import { Suspense, useCallback, useEffect, useState } from "react";
import { useParams, useSearchParams } from "next/navigation";
import { ArrowLeft, Flower2, GitFork, Users } 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 { crossTypeLabel } from "../../constants";
import { fetchCrossDetail } from "../../api";
import { CrossParentsPanel } from "../../components/CrossParentsPanel";
import { CrossPollinationEventPanel } from "../../components/CrossPollinationEventPanel";
import type { CrossRecord } from "../../types";

type CrossDetailTab = "parents" | "pollination";

function isCrossDetailTab(value: string | null): value is CrossDetailTab {
  return value === "parents" || value === "pollination";
}

function CrossDetailPageContent() {
  const params = useParams<{ crossDbId: string }>();
  const searchParams = useSearchParams();
  const crossDbId = decodeURIComponent(params.crossDbId);

  const initialTab = isCrossDetailTab(searchParams.get("tab")) ? searchParams.get("tab") as CrossDetailTab : "parents";
  const [activeTab, setActiveTab] = useState<CrossDetailTab>(initialTab);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [detail, setDetail] = useState<CrossRecord | null>(null);

  const loadDetail = useCallback(async () => {
    const record = await fetchCrossDetail(crossDbId);
    setDetail(record);
  }, [crossDbId]);

  useEffect(() => {
    setActiveTab(initialTab);
  }, [initialTab]);

  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]);

  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 || "实际杂交不存在"}
        <div className="mt-4">
          <Button asChild variant="outline">
            <Link href="/germplasm/cross-pedigree?tab=crosses"><ArrowLeft className="mr-2 h-4 w-4" />返回列表</Link>
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="flex min-h-full flex-col gap-4">
      <Button asChild variant="outline" size="sm" className="w-fit">
        <Link href="/germplasm/cross-pedigree?tab=crosses"><ArrowLeft className="mr-2 h-4 w-4" />返回 Cross 列表</Link>
      </Button>

      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2 text-lg">
            <GitFork className="h-5 w-5 text-green-500" />
            {detail.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">Cross ID：</span>{detail.id}</div>
          <div><span className="text-slate-500">杂交项目：</span>{detail.crossing_project_name || detail.crossing_project_id || "—"}</div>
          <div><span className="text-slate-500">来源计划杂交：</span>{detail.plannedCrossName || "—"}</div>
          <div><span className="text-slate-500">类型：</span>{crossTypeLabel(detail.cross_type)}</div>
          <div><span className="text-slate-500">授粉事件数：</span>{detail.pollination_events.length}</div>
        </CardContent>
      </Card>

      {detail.crossing_project_id ? (
        <Button asChild variant="outline" size="sm" className="w-fit">
          <Link href={`/germplasm/cross-pedigree/projects/${encodeURIComponent(detail.crossing_project_id)}`}>
            查看所属杂交项目
          </Link>
        </Button>
      ) : null}

      <Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as CrossDetailTab)} className="flex min-h-full flex-col gap-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="parents" className="gap-2"><Users className="h-4 w-4" />Parents 亲本</TabsTrigger>
          <TabsTrigger value="pollination" className="gap-2"><Flower2 className="h-4 w-4" />Pollination Events</TabsTrigger>
        </TabsList>

        {activeTab === "parents" ? (
          <TabsContent value="parents" className="mt-0">
            <CrossParentsPanel
              crossId={detail.id}
              planned={false}
              crossName={detail.name}
              crossingProjectId={detail.crossing_project_id}
              crossingProjectName={detail.crossing_project_name}
              parent1={detail.parent1}
              parent2={detail.parent2}
              onChanged={loadDetail}
            />
          </TabsContent>
        ) : null}

        {activeTab === "pollination" ? (
          <TabsContent value="pollination" className="mt-0">
            <CrossPollinationEventPanel
              crossId={detail.id}
              crossName={detail.name}
              events={detail.pollination_events}
              onChanged={loadDetail}
            />
          </TabsContent>
        ) : null}
      </Tabs>
    </div>
  );
}

export default function CrossDetailPage() {
  return (
    <Suspense fallback={null}>
      <CrossDetailPageContent />
    </Suspense>
  );
}
