"use client";

import Link from "next/link";
import { Suspense, useCallback, useEffect, useMemo, useState } from "react";
import { useParams, useSearchParams } from "next/navigation";
import {
  ArrowLeft,
  Building2,
  Dna,
  GitBranch,
  GitFork,
  Globe2,
  Hash,
  ListChecks,
  MapPin,
  Package,
  Tags,
} 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 { fetchGermplasmDetail } from "../api";
import {
  GermplasmAttributePanel,
  GermplasmCrossParentPanel,
  GermplasmPedigreePanel,
  GermplasmSeedLotPanel,
} from "../components/GermplasmDetailRelatedPanels";
import {
  GermplasmDonorPanel,
  GermplasmInstitutePanel,
  GermplasmOriginPanel,
  GermplasmProfileSummaryHint,
  GermplasmSynonymPanel,
  GermplasmTaxonPanel,
} from "../components/GermplasmProfilePanels";
import type { GermplasmProfileTab } from "../profileTypes";

const DETAIL_TABS: GermplasmProfileTab[] = [
  "attributes",
  "donors",
  "institutes",
  "origins",
  "synonyms",
  "taxons",
  "pedigree",
  "seed-lots",
  "cross-parents",
];

function isDetailTab(value: string | null): value is GermplasmProfileTab {
  return DETAIL_TABS.includes(value as GermplasmProfileTab);
}

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

  const initialTab = useMemo(() => {
    const tab = searchParams.get("tab");
    return isDetailTab(tab) ? tab : "attributes";
  }, [searchParams]);

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

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

  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/germplasm"><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/germplasm"><ArrowLeft className="mr-2 h-4 w-4" />返回种质列表</Link>
      </Button>

      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2 text-lg">
            <Dna className="h-5 w-5 text-teal-500" />
            {detail.germplasm_name || detail.default_display_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">Germplasm ID：</span>{detail.id}</div>
          <div><span className="text-slate-500">登录号：</span>{detail.accession_number || "—"}</div>
          <div><span className="text-slate-500">PUI：</span>{detail.germplasmpui || "—"}</div>
          <div><span className="text-slate-500">作物：</span>{detail.crop_name || detail.crop_id || "—"}</div>
          <div><span className="text-slate-500">育种方法：</span>{detail.breeding_method_name || "—"}</div>
          <div><span className="text-slate-500">属 / 种：</span>{[detail.genus, detail.species].filter(Boolean).join(" ") || "—"}</div>
          <div><span className="text-slate-500">来源国家：</span>{detail.country_of_origin_code || "—"}</div>
          <div><span className="text-slate-500">集合：</span>{detail.collection || "—"}</div>
        </CardContent>
      </Card>

      <GermplasmProfileSummaryHint />

      <Tabs
        value={activeTab}
        onValueChange={(value) => setActiveTab(value as GermplasmProfileTab)}
        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="attributes" className="gap-2"><ListChecks className="h-4 w-4" />Attributes</TabsTrigger>
          <TabsTrigger value="donors" className="gap-2"><Building2 className="h-4 w-4" />Donor</TabsTrigger>
          <TabsTrigger value="institutes" className="gap-2"><Globe2 className="h-4 w-4" />Institute</TabsTrigger>
          <TabsTrigger value="origins" className="gap-2"><MapPin className="h-4 w-4" />Origin</TabsTrigger>
          <TabsTrigger value="synonyms" className="gap-2"><Tags className="h-4 w-4" />Synonym</TabsTrigger>
          <TabsTrigger value="taxons" className="gap-2"><Hash className="h-4 w-4" />Taxon</TabsTrigger>
          <TabsTrigger value="pedigree" className="gap-2"><GitBranch className="h-4 w-4" />Pedigree</TabsTrigger>
          <TabsTrigger value="seed-lots" className="gap-2"><Package className="h-4 w-4" />Seed Lots</TabsTrigger>
          <TabsTrigger value="cross-parents" className="gap-2"><GitFork className="h-4 w-4" />Cross Parent</TabsTrigger>
        </TabsList>

        <TabsContent value="attributes" className="mt-0 min-h-0 flex-1">
          <GermplasmAttributePanel germplasmDbId={germplasmDbId} />
        </TabsContent>
        <TabsContent value="donors" className="mt-0 min-h-0 flex-1">
          <GermplasmDonorPanel germplasmDbId={germplasmDbId} />
        </TabsContent>
        <TabsContent value="institutes" className="mt-0 min-h-0 flex-1">
          <GermplasmInstitutePanel germplasmDbId={germplasmDbId} />
        </TabsContent>
        <TabsContent value="origins" className="mt-0 min-h-0 flex-1">
          <GermplasmOriginPanel germplasmDbId={germplasmDbId} />
        </TabsContent>
        <TabsContent value="synonyms" className="mt-0 min-h-0 flex-1">
          <GermplasmSynonymPanel germplasmDbId={germplasmDbId} />
        </TabsContent>
        <TabsContent value="taxons" className="mt-0 min-h-0 flex-1">
          <GermplasmTaxonPanel germplasmDbId={germplasmDbId} />
        </TabsContent>
        <TabsContent value="pedigree" className="mt-0 min-h-0 flex-1">
          <GermplasmPedigreePanel
            germplasmDbId={germplasmDbId}
            germplasmName={detail.germplasm_name || detail.default_display_name}
          />
        </TabsContent>
        <TabsContent value="seed-lots" className="mt-0 min-h-0 flex-1">
          <GermplasmSeedLotPanel germplasmDbId={germplasmDbId} />
        </TabsContent>
        <TabsContent value="cross-parents" className="mt-0 min-h-0 flex-1">
          <GermplasmCrossParentPanel germplasmDbId={germplasmDbId} />
        </TabsContent>
      </Tabs>
    </div>
  );
}

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