"use client";

import Link from "next/link";
import { Suspense, useCallback, useEffect, useMemo, useState } from "react";
import { useParams, useSearchParams } from "next/navigation";
import { ArrowLeft, ArrowLeftRight, Layers, Package } 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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { fetchSeedLotDetail } from "../api";
import { SeedLotContentMixturePanel } from "../components/SeedLotContentMixturePanel";
import { SeedLotTransactionPanel } from "../components/SeedLotTransactionPanel";
import {
  STOCK_STATUS_LABEL,
  resolveStockStatus,
  type SeedLotDetailTab,
} from "../types";

function isSeedLotDetailTab(value: string | null): value is SeedLotDetailTab {
  return value === "mixture" || value === "transactions";
}

function StockStatusBadge({ amount }: { amount: number | null | undefined }) {
  const status = resolveStockStatus(amount);
  const className = status === "depleted"
    ? "bg-red-50 text-red-700 dark:bg-red-400/10 dark:text-red-200"
    : status === "low"
      ? "bg-amber-50 text-amber-700 dark:bg-amber-400/10 dark:text-amber-200"
      : "bg-emerald-50 text-emerald-700 dark:bg-emerald-400/10 dark:text-emerald-200";
  return <Badge variant="outline" className={className}>{STOCK_STATUS_LABEL[status]}</Badge>;
}

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

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

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

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

  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/seed-lot"><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/seed-lot"><ArrowLeft className="mr-2 h-4 w-4" />返回批次列表</Link>
      </Button>

      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2 text-lg">
            <Package className="h-5 w-5 text-lime-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">批次 ID：</span>{detail.id}</div>
          <div className="flex items-center gap-2">
            <span className="text-slate-500">库存：</span>
            {detail.amount ?? "—"}{detail.units ? ` ${detail.units}` : ""}
            <StockStatusBadge amount={detail.amount} />
          </div>
          <div><span className="text-slate-500">项目：</span>{detail.program_name || "—"}</div>
          <div><span className="text-slate-500">地点：</span>{detail.location_name || "—"}</div>
          <div><span className="text-slate-500">库位：</span>{detail.storage_location || "—"}</div>
          <div><span className="text-slate-500">来源集合：</span>{detail.source_collection || "—"}</div>
          <div><span className="text-slate-500">创建：</span>{detail.created_date || "—"}</div>
          <div><span className="text-slate-500">最后更新：</span>{detail.last_updated || "—"}</div>
          <div className="sm:col-span-2 lg:col-span-4">
            <span className="text-slate-500">说明：</span>{detail.seed_lot_description || "—"}
          </div>
        </CardContent>
      </Card>

      <Tabs
        value={activeTab}
        onValueChange={(value) => setActiveTab(value as SeedLotDetailTab)}
        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="mixture" className="gap-2">
            <Layers className="h-4 w-4" />
            Content Mixture
          </TabsTrigger>
          <TabsTrigger value="transactions" className="gap-2">
            <ArrowLeftRight className="h-4 w-4" />
            Transactions
          </TabsTrigger>
        </TabsList>

        <TabsContent value="mixture" className="mt-0 min-h-0 flex-1">
          <SeedLotContentMixturePanel seedLotDbId={seedLotDbId} />
        </TabsContent>

        <TabsContent value="transactions" className="mt-0 min-h-0 flex-1">
          <SeedLotTransactionPanel
            seedLotDbId={seedLotDbId}
            embedded
            onChanged={loadDetail}
          />
        </TabsContent>
      </Tabs>
    </div>
  );
}

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