"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { ArrowLeft, 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 { crossTypeLabel, plannedStatusLabel } from "../../constants";
import { fetchPlannedCrossDetail } from "../../api";
import { CrossParentsPanel } from "../../components/CrossParentsPanel";
import type { PlannedCrossRecord } from "../../types";

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

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

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

  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-emerald-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>{crossTypeLabel(detail.cross_type)}</div>
          <div><span className="text-slate-500">状态：</span>{plannedStatusLabel(detail.status)}</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}

      <div className="flex items-center gap-2 text-sm text-slate-500">
        <Users className="h-4 w-4" />
        Parents Tab
      </div>

      <CrossParentsPanel
        crossId={detail.id}
        planned
        crossName={detail.name}
        crossingProjectId={detail.crossing_project_id}
        crossingProjectName={detail.crossing_project_name}
        parent1={detail.parent1}
        parent2={detail.parent2}
        onChanged={loadDetail}
      />
    </div>
  );
}
