"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { ArrowLeft, GitBranch, Map, Sigma } 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 { LinkageGroupPanel } from "../../components/LinkageGroupPanel";
import { MarkerPositionPanel } from "../../components/MarkerPositionPanel";
import { fetchGenomeMapDetail } from "../../api";
import { formatPublishedDate } from "../../genomeMapUtils";
import type { GenomeMapDetail } from "../../types";

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

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

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

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

  const hasDependencies = (detail.linkage_group_count ?? detail.linkageGroups.length) > 0
    || (detail.marker_count ?? detail.markerPositions.length) > 0;

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

      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2 text-lg">
            <Map className="h-5 w-5 text-teal-500" />
            {detail.map_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">Map ID：</span>{detail.id}</div>
          <div><span className="text-slate-500">作物：</span>{detail.common_crop_name || "—"}</div>
          <div><span className="text-slate-500">类型：</span>{detail.type || "—"}</div>
          <div><span className="text-slate-500">单位：</span>{detail.unit || "—"}</div>
          <div><span className="text-slate-500">学名：</span>{detail.scientific_name || "—"}</div>
          <div><span className="text-slate-500">Map PUI：</span>{detail.map_pui || "—"}</div>
          <div><span className="text-slate-500">发表日期：</span>{formatPublishedDate(detail.published_date)}</div>
          <div><span className="text-slate-500">连锁群数：</span>{detail.linkage_group_count ?? detail.linkageGroups.length}</div>
          <div><span className="text-slate-500">Marker 数：</span>{detail.marker_count ?? detail.markerPositions.length}</div>
          <div className="sm:col-span-2"><span className="text-slate-500">文档：</span>{detail.documentation_url || "—"}</div>
          <div className="sm:col-span-2"><span className="text-slate-500">备注：</span>{detail.comments || "—"}</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">
          删除图谱前请先移除下属连锁群与 Marker Position。
        </p>
      ) : null}

      <div className="flex flex-wrap gap-2">
        <Button asChild variant="outline" size="sm">
          <Link href={`/genotyping/genome-map?tab=linkage-groups&map_db_id=${encodeURIComponent(detail.id)}`}>
            <GitBranch className="mr-2 h-4 w-4" />
            在 Linkage Group 列表中查看
          </Link>
        </Button>
        <Button asChild variant="outline" size="sm">
          <Link href="/genotyping/variant">
            <Sigma className="mr-2 h-4 w-4" />
            前往 Variant 管理
          </Link>
        </Button>
      </div>

      <LinkageGroupPanel mapDbId={mapDbId} onChanged={loadDetail} />
      <MarkerPositionPanel mapDbId={mapDbId} onChanged={loadDetail} />
    </div>
  );
}
