"use client";

import Link from "next/link";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useParams } from "next/navigation";
import { ArrowLeft, BookOpen, Dna } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField } from "@/components/brapi/BrapiEntityPage";
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 {
  createReferenceBasesRow,
  deleteReferenceBasesRow,
  fetchReferenceBasesRows,
  fetchReferenceDetail,
  normalizeReferenceBasesFormData,
  updateReferenceBasesRow,
} from "../../api";
import { truncateText } from "../../referenceUtils";
import type { ReferenceRecord } from "../../types";

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

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

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

  const defaultFormValues = useMemo(() => ({ reference_id: referenceDbId }), [referenceDbId]);

  const loadBases = useCallback(async () => {
    const rows = await fetchReferenceBasesRows(referenceDbId);
    return rows as unknown as Record<string, unknown>[];
  }, [referenceDbId]);

  const fetchRecord = useCallback(async (id: string) => {
    const rows = await fetchReferenceBasesRows(referenceDbId);
    const found = rows.find((row) => row.id === id);
    if (!found) throw new Error("ReferenceBases 记录不存在");
    return normalizeReferenceBasesFormData({ ...found, reference_id: referenceDbId });
  }, [referenceDbId]);

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "id", label: "ReferenceBases ID", type: "text", placeholder: "留空则系统自动生成" },
    { key: "page_number", label: "分页序号", type: "number", required: true, placeholder: "0 起" },
    {
      key: "bases",
      label: "碱基序列片段",
      type: "textarea",
      required: true,
      colSpan: 2,
      placeholder: "ACGT...（最多 2048 字符，建议文件导入）",
    },
  ], []);

  const lengthMismatch = detail?.length != null
    && detail.bases_total_length != null
    && Number(detail.length) > 0
    && Number(detail.bases_total_length) !== Number(detail.length);

  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 || "Reference 不存在"}
        <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={detail.reference_set_id ? `/genotyping/reference-set/referencesets/${encodeURIComponent(detail.reference_set_id)}` : "/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">
            <BookOpen className="h-5 w-5 text-emerald-500" />
            {detail.reference_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">Reference ID：</span>{detail.id}</div>
          <div><span className="text-slate-500">ReferenceSet：</span>{detail.reference_set_name || detail.reference_set_id || "—"}</div>
          <div><span className="text-slate-500">序列长度：</span>{detail.length ?? "—"}</div>
          <div><span className="text-slate-500">MD5：</span>{detail.md5checksum || "—"}</div>
          <div><span className="text-slate-500">来源差异：</span>{detail.source_divergence ?? "—"}</div>
          <div><span className="text-slate-500">Bases 分页数：</span>{detail.bases_page_count ?? 0}</div>
          <div><span className="text-slate-500">Bases 总长度：</span>{detail.bases_total_length ?? 0}</div>
        </CardContent>
      </Card>

      {lengthMismatch ? (
        <Badge variant="outline" className="w-fit border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-200">
          Bases 总长度 ({detail.bases_total_length}) 与声明长度 ({detail.length}) 不一致，请检查分页数据
        </Badge>
      ) : null}

      <BrapiEntityPage
        useEnhancedDialog
        icon={Dna}
        iconBg="bg-gradient-to-br from-cyan-500 to-blue-600"
        title="ReferenceBases 序列分页"
        description="按 page_number 维护碱基片段；长序列建议走文件导入，不建议手工逐页录入。"
        addLabel="新增分页"
        defaultFormValues={defaultFormValues}
        columns={[
          { key: "page_number", label: "分页序号" },
          { key: "bases", label: "碱基片段", render: (value) => truncateText(value) },
        ]}
        fields={fields}
        data={[]}
        stats={[{
          label: "/brapi/v2/referencebases",
          value: "Admin",
          className: "bg-cyan-50 text-cyan-700 dark:bg-cyan-400/10 dark:text-cyan-200",
        }]}
        loadData={loadBases}
        fetchRecord={fetchRecord}
        createRecord={(payload) => createReferenceBasesRow({ ...payload, reference_id: referenceDbId }) as unknown as Promise<Record<string, unknown>>}
        updateRecord={(id, payload) => updateReferenceBasesRow(id, { ...payload, reference_id: referenceDbId }) as unknown as Promise<Record<string, unknown>>}
        deleteRecord={deleteReferenceBasesRow}
      />
    </div>
  );
}
