"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { ArrowLeft, GitBranch, Map } 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 { MarkerPositionEntityPage } from "../../../../components/MarkerPositionEntityPage";
import { fetchGenomeMapDetail, fetchLinkageGroupDetail } from "../../../../api";
import type { GenomeMapRecord, LinkageGroupRecord } from "../../../../types";

export default function LinkageGroupDetailPage() {
  const params = useParams<{ mapDbId: string; linkageGroupDbId: string }>();
  const mapDbId = decodeURIComponent(params.mapDbId);
  const linkageGroupDbId = decodeURIComponent(params.linkageGroupDbId);

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [mapDetail, setMapDetail] = useState<GenomeMapRecord | null>(null);
  const [linkageGroup, setLinkageGroup] = useState<LinkageGroupRecord | null>(null);

  const loadDetail = useCallback(async () => {
    const [map, group] = await Promise.all([
      fetchGenomeMapDetail(mapDbId),
      fetchLinkageGroupDetail(mapDbId, linkageGroupDbId),
    ]);
    if (!group) throw new Error("连锁群不存在");
    setMapDetail(map);
    setLinkageGroup(group);
  }, [mapDbId, linkageGroupDbId]);

  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 || !linkageGroup || !mapDetail) {
    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="/genotyping/genome-map?tab=linkage-groups">
              <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={`/genotyping/genome-map/maps/${encodeURIComponent(mapDbId)}`}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          返回图谱详情
        </Link>
      </Button>

      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2 text-lg">
            <GitBranch className="h-5 w-5 text-emerald-500" />
            {linkageGroup.linkage_group_name || linkageGroup.id}
          </CardTitle>
        </CardHeader>
        <CardContent className="grid gap-3 text-sm sm:grid-cols-2 lg:grid-cols-4">
          <div><span className="text-slate-500">LinkageGroup ID：</span>{linkageGroup.id}</div>
          <div>
            <span className="text-slate-500">所属图谱：</span>
            <Link
              href={`/genotyping/genome-map/maps/${encodeURIComponent(mapDbId)}`}
              className="text-teal-600 hover:underline dark:text-teal-400"
            >
              {mapDetail.map_name || mapDbId}
            </Link>
          </div>
          <div><span className="text-slate-500">最大位置：</span>{linkageGroup.max_position ?? "—"}</div>
          <div className="flex items-center gap-2">
            <span className="text-slate-500">Marker 数：</span>
            <Badge variant="outline">{linkageGroup.marker_count ?? 0}</Badge>
          </div>
        </CardContent>
      </Card>

      <div className="flex flex-wrap gap-2">
        <Button asChild variant="outline" size="sm">
          <Link href={`/genotyping/genome-map?tab=marker-positions&map_db_id=${encodeURIComponent(mapDbId)}&linkage_group_name=${encodeURIComponent(linkageGroup.linkage_group_name || "")}`}>
            <Map className="mr-2 h-4 w-4" />
            在 Marker Position 列表中查看
          </Link>
        </Button>
      </div>

      <MarkerPositionEntityPage
        mapDbId={mapDbId}
        linkageGroupDbId={linkageGroupDbId}
        linkageGroupName={linkageGroup.linkage_group_name}
        onChanged={loadDetail}
        defaultFormValues={{ linkage_group_id: linkageGroupDbId }}
      />
    </div>
  );
}
