"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { MapPin } 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 { fetchMarkerPositionsByVariantId } from "../../genome-map/api";
import type { MarkerPositionRecord } from "../../genome-map/types";

interface VariantMarkerPositionCardProps {
  variantDbId: string;
}

export function VariantMarkerPositionCard({ variantDbId }: VariantMarkerPositionCardProps) {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [rows, setRows] = useState<MarkerPositionRecord[]>([]);

  useEffect(() => {
    let mounted = true;
    setLoading(true);
    setError(null);
    fetchMarkerPositionsByVariantId(variantDbId)
      .then((result) => {
        if (!mounted) return;
        setRows(result);
      })
      .catch((event) => {
        if (!mounted) return;
        setError(event instanceof Error ? event.message : "加载 Marker Position 失败");
      })
      .finally(() => {
        if (mounted) setLoading(false);
      });
    return () => { mounted = false; };
  }, [variantDbId]);

  return (
    <Card>
      <CardHeader className="pb-3">
        <CardTitle className="flex items-center gap-2 text-base">
          <MapPin className="h-4 w-4 text-emerald-500" />
          Marker Position
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-3 text-sm">
        {loading ? (
          <Skeleton className="h-24 w-full" />
        ) : error ? (
          <p className="text-destructive">{error}</p>
        ) : rows.length === 0 ? (
          <p className="text-slate-600 dark:text-slate-300">
            该 Variant 尚未关联遗传图谱位置。
          </p>
        ) : (
          <div className="overflow-x-auto rounded-lg border border-slate-200 dark:border-slate-800">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>图谱</TableHead>
                  <TableHead>连锁群</TableHead>
                  <TableHead>位置</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {rows.map((row) => (
                  <TableRow key={row.id}>
                    <TableCell>
                      {row.map_db_id ? (
                        <Link
                          href={`/genotyping/genome-map/maps/${encodeURIComponent(row.map_db_id)}`}
                          className="text-teal-600 hover:underline dark:text-teal-400"
                        >
                          {row.map_name || row.map_db_id}
                        </Link>
                      ) : "—"}
                    </TableCell>
                    <TableCell>
                      {row.linkage_group_db_id && row.map_db_id ? (
                        <Link
                          href={`/genotyping/genome-map/maps/${encodeURIComponent(row.map_db_id)}/linkage-groups/${encodeURIComponent(row.linkage_group_db_id)}`}
                          className="text-teal-600 hover:underline dark:text-teal-400"
                        >
                          {row.linkage_group_name || row.linkage_group_db_id}
                        </Link>
                      ) : (row.linkage_group_name || "—")}
                    </TableCell>
                    <TableCell>{row.position ?? "—"}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        )}

        <div className="flex flex-wrap gap-2">
          <Button asChild variant="link" className="h-auto px-0 text-cyan-600 dark:text-cyan-400">
            <Link href={`/genotyping/genome-map?tab=marker-positions&variant_db_id=${encodeURIComponent(variantDbId)}`}>
              在 GenomeMap 模块维护 Marker Position
            </Link>
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
