"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { ArrowLeft, GitFork, Network, 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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { crossTypeLabel, plannedStatusLabel } from "../../constants";
import { fetchCrossingProjectDetailExtended } from "../../api";
import type { CrossingProjectDetail } from "../../types";

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

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [detail, setDetail] = useState<CrossingProjectDetail | null>(null);

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

  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"><ArrowLeft className="mr-2 h-4 w-4" />返回列表</Link>
          </Button>
        </div>
      </div>
    );
  }

  const hasDependencies = detail.plannedCrosses.length > 0
    || detail.actualCrosses.length > 0
    || detail.pedigreeNodes.length > 0;

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

      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2 text-lg">
            <Network 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><span className="text-slate-500">Program：</span>{detail.program_name || detail.program_id || "—"}</div>
          <div><span className="text-slate-500">计划杂交：</span>{detail.plannedCrosses.length}</div>
          <div><span className="text-slate-500">实际杂交：</span>{detail.actualCrosses.length}</div>
          <div className="sm:col-span-2 lg:col-span-4"><span className="text-slate-500">说明：</span>{detail.description || "—"}</div>
        </CardContent>
      </Card>

      {hasDependencies ? (
        <p className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-200">
          删除杂交项目前请先清理下属 Cross、Cross Parent 与 Pedigree Node 引用。
        </p>
      ) : null}

      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base">计划杂交</CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow className="bg-slate-50 dark:bg-slate-900">
                <TableHead>名称</TableHead>
                <TableHead>类型</TableHead>
                <TableHead>状态</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {detail.plannedCrosses.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={3} className="py-6 text-center text-sm text-slate-400">暂无计划杂交</TableCell>
                </TableRow>
              ) : detail.plannedCrosses.map((row) => (
                <TableRow key={row.id}>
                  <TableCell>
                    <Link
                      href={`/germplasm/cross-pedigree/planned-crosses/${encodeURIComponent(row.id)}`}
                      className="font-medium text-emerald-600 hover:underline dark:text-emerald-400"
                    >
                      {row.name || row.id}
                    </Link>
                  </TableCell>
                  <TableCell>{crossTypeLabel(row.cross_type)}</TableCell>
                  <TableCell>{plannedStatusLabel(row.status)}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base">实际杂交</CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow className="bg-slate-50 dark:bg-slate-900">
                <TableHead>名称</TableHead>
                <TableHead>来源计划杂交</TableHead>
                <TableHead>类型</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {detail.actualCrosses.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={3} className="py-6 text-center text-sm text-slate-400">暂无实际杂交</TableCell>
                </TableRow>
              ) : detail.actualCrosses.map((row) => (
                <TableRow key={row.id}>
                  <TableCell>
                    <Link
                      href={`/germplasm/cross-pedigree/crosses/${encodeURIComponent(row.id)}`}
                      className="font-medium text-green-600 hover:underline dark:text-green-400"
                    >
                      {row.name || row.id}
                    </Link>
                  </TableCell>
                  <TableCell>{row.plannedCrossName || "—"}</TableCell>
                  <TableCell>{crossTypeLabel(row.cross_type)}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2 text-base">
            <Share2 className="h-4 w-4" />
            关联 Pedigree Node
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow className="bg-slate-50 dark:bg-slate-900">
                <TableHead>材料</TableHead>
                <TableHead>杂交年份</TableHead>
                <TableHead>家系编号</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {detail.pedigreeNodes.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={3} className="py-6 text-center text-sm text-slate-400">暂无关联系谱节点</TableCell>
                </TableRow>
              ) : detail.pedigreeNodes.map((row) => {
                const germplasmId = String(row.germplasm_id ?? row.id ?? "");
                return (
                  <TableRow key={row.id}>
                    <TableCell>
                      {germplasmId ? (
                        <Link
                          href={`/germplasm/cross-pedigree/pedigree-nodes/${encodeURIComponent(germplasmId)}`}
                          className="font-medium text-sky-600 hover:underline dark:text-sky-400"
                        >
                          {row.germplasm_name || germplasmId}
                        </Link>
                      ) : (row.germplasm_name || "—")}
                    </TableCell>
                    <TableCell>{row.crossing_year ?? "—"}</TableCell>
                    <TableCell>{row.family_code || "—"}</TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <div className="flex flex-wrap gap-2">
        <Button asChild variant="outline" size="sm">
          <Link href={`/germplasm/cross-pedigree?tab=crosses`}>
            <GitFork className="mr-2 h-4 w-4" />
            前往 Cross 管理
          </Link>
        </Button>
      </div>
    </div>
  );
}
