"use client";

import Link from "next/link";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useParams } from "next/navigation";
import { ArrowLeft, BookOpen, Layers, Sigma } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField } from "@/components/brapi/BrapiEntityPage";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import {
  fetchReferenceRows,
  fetchReferenceSetDetail,
} from "../../api";
import { boolLabel } from "../../referenceUtils";
import type { ReferenceRecord, ReferenceSetRecord } from "../../types";

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

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

  useEffect(() => {
    let mounted = true;
    setLoading(true);
    setError(null);
    fetchReferenceSetDetail(referenceSetDbId)
      .then((record) => {
        if (!mounted) return;
        setDetail(record);
      })
      .catch((event) => {
        if (!mounted) return;
        setError(event instanceof Error ? event.message : "加载 ReferenceSet 详情失败");
      })
      .finally(() => {
        if (mounted) setLoading(false);
      });
    return () => { mounted = false; };
  }, [referenceSetDbId]);

  const loadReferences = useCallback(async () => {
    const rows = await fetchReferenceRows({ reference_set_id: referenceSetDbId });
    return rows as unknown as Record<string, unknown>[];
  }, [referenceSetDbId]);

  const referenceColumns = useMemo(() => [
    {
      key: "reference_name",
      label: "序列名称",
      render: (value: unknown, row: Record<string, unknown>) => {
        const id = String(row.id ?? row.referenceDbId ?? "");
        const name = String(value ?? "—");
        if (!id) return name;
        return (
          <Link href={`/genotyping/reference-set/references/${encodeURIComponent(id)}`} className="font-medium text-emerald-600 hover:underline dark:text-emerald-400">
            {name}
          </Link>
        );
      },
    },
    { key: "length", label: "长度" },
    { key: "bases_page_count", label: "Bases 分页数" },
    { key: "md5checksum", label: "MD5" },
  ], []);

  const emptyFields = useMemo<BrapiFormField[]>(() => [], []);

  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 || "ReferenceSet 不存在"}
        <div className="mt-4">
          <Button asChild variant="outline">
            <Link href="/genotyping/reference-set"><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/reference-set"><ArrowLeft className="mr-2 h-4 w-4" />返回 ReferenceSet 列表</Link>
      </Button>

      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2 text-lg">
            <Layers className="h-5 w-5 text-indigo-500" />
            {detail.reference_set_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">ReferenceSet ID：</span>{detail.id}</div>
          <div><span className="text-slate-500">Assembly PUI：</span>{detail.assembly_pui || "—"}</div>
          <div><span className="text-slate-500">物种：</span>{detail.species_ontology_term || "—"}</div>
          <div><span className="text-slate-500">来源 Germplasm：</span>{detail.source_germplasm_name || "—"}</div>
          <div><span className="text-slate-500">Reference 数：</span>{detail.reference_count ?? 0}</div>
          <div><span className="text-slate-500">VariantSet 数：</span>{detail.variantset_count ?? 0}</div>
          <div><span className="text-slate-500">Variant 数：</span>{detail.variant_count ?? 0}</div>
          <div><span className="text-slate-500">派生参考：</span>{boolLabel(detail.is_derived)}</div>
          <div className="sm:col-span-2"><span className="text-slate-500">说明：</span>{detail.description || "—"}</div>
        </CardContent>
      </Card>

      <div className="flex flex-wrap gap-2">
        <Button asChild variant="outline" size="sm">
          <Link href={`/genotyping/reference-set?tab=references&reference_set_id=${encodeURIComponent(detail.id)}`}>
            <BookOpen className="mr-2 h-4 w-4" />
            在 Reference 列表中查看
          </Link>
        </Button>
        <Button asChild variant="outline" size="sm">
          <Link href="/genotyping/variant">
            <Sigma className="mr-2 h-4 w-4" />
            前往 Variant / VariantSet
          </Link>
        </Button>
      </div>

      <BrapiEntityPage
        icon={BookOpen}
        iconBg="bg-gradient-to-br from-emerald-500 to-teal-600"
        title="下属 Reference"
        description="该 ReferenceSet 下的参考序列列表，点击名称进入 Reference 详情维护 Bases。"
        columns={referenceColumns}
        fields={emptyFields}
        data={[]}
        loadData={loadReferences}
      />
    </div>
  );
}
