"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { ArrowLeft, FlaskConical, Pencil } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { TrialMetaDialog } from "../components/TrialMetaDialog";
import { fetchTrialDetail, fetchTrialOptions } from "../api";
import type { SelectOption, TrialRecord } from "../types";

export default function TrialDetailPage() {
  const params = useParams<{ trialDbId: string }>();
  const trialDbId = decodeURIComponent(params.trialDbId ?? "");
  const [record, setRecord] = useState<TrialRecord | null>(null);
  const [personOptions, setPersonOptions] = useState<SelectOption[]>([]);
  const [programOptions, setProgramOptions] = useState<SelectOption[]>([]);
  const [cropOptions, setCropOptions] = useState<SelectOption[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [editOpen, setEditOpen] = useState(false);

  const loadDetail = useCallback(async () => {
    if (!trialDbId) return;
    setLoading(true);
    setError(null);
    try {
      const [options, detail] = await Promise.all([fetchTrialOptions(), fetchTrialDetail(trialDbId)]);
      setPersonOptions(options.persons);
      setProgramOptions(options.programs);
      setCropOptions(options.crops);
      setRecord(detail);
    } catch (event) {
      setError(event instanceof Error ? event.message : "加载失败");
      setRecord(null);
    } finally {
      setLoading(false);
    }
  }, [trialDbId]);

  useEffect(() => {
    loadDetail().catch(() => undefined);
  }, [loadDetail]);

  if (!trialDbId) {
    return <div className="p-6 text-sm text-destructive">缺少试验 ID</div>;
  }

  const contacts = record?.trialContacts ?? record?.contacts ?? [];
  const publications = record?.trialPublications ?? record?.publications ?? [];

  return (
    <div className="flex min-h-full flex-col">
      <div className="mb-5 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
        <div className="flex items-start gap-3">
          <Button variant="outline" size="icon" className="shrink-0" asChild>
            <Link href="/project/trial" aria-label="返回列表">
              <ArrowLeft className="h-4 w-4" />
            </Link>
          </Button>
          <div className="flex items-center gap-3">
            <div className="rounded-xl bg-gradient-to-br from-indigo-500 to-violet-600 p-2.5">
              <FlaskConical className="h-5 w-5 text-white" />
            </div>
            <div>
              <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-50">
                {record?.trial_name || record?.trialName || "Trial 详情"}
              </h2>
              <p className="mt-0.5 text-sm text-slate-500 dark:text-slate-400">试验基本信息、联系人与出版物</p>
            </div>
          </div>
        </div>
        {record ? (
          <Button variant="outline" className="gap-2" onClick={() => setEditOpen(true)}>
            <Pencil className="h-4 w-4" />
            编辑试验
          </Button>
        ) : null}
      </div>

      {error ? (
        <div className="mb-4 rounded-xl border border-destructive/20 bg-destructive/10 px-4 py-3 text-sm text-destructive">
          {error}
        </div>
      ) : null}

      <div className="mb-5 rounded-xl border border-slate-200 bg-white p-4 dark:border-slate-800 dark:bg-slate-950">
        {loading ? (
          <div className="grid gap-3 md:grid-cols-2">
            {Array.from({ length: 6 }).map((_, index) => (
              <Skeleton key={index} className="h-5 w-full" />
            ))}
          </div>
        ) : record ? (
          <dl className="grid gap-3 text-sm md:grid-cols-2">
            <div>
              <dt className="text-xs text-slate-500 dark:text-slate-400">试验 ID</dt>
              <dd className="mt-0.5 break-all font-medium text-slate-800 dark:text-slate-100">{record.trialDbId}</dd>
            </div>
            <div>
              <dt className="text-xs text-slate-500 dark:text-slate-400">项目</dt>
              <dd className="mt-0.5 text-slate-800 dark:text-slate-100">{record.program_name || record.programName || "—"}</dd>
            </div>
            <div>
              <dt className="text-xs text-slate-500 dark:text-slate-400">作物</dt>
              <dd className="mt-0.5 text-slate-800 dark:text-slate-100">{record.crop_name || record.cropName || "—"}</dd>
            </div>
            <div>
              <dt className="text-xs text-slate-500 dark:text-slate-400">状态</dt>
              <dd className="mt-0.5 text-slate-800 dark:text-slate-100">
                {record.active === true ? "活跃" : record.active === false ? "停用" : "—"}
              </dd>
            </div>
            <div>
              <dt className="text-xs text-slate-500 dark:text-slate-400">开始 / 结束</dt>
              <dd className="mt-0.5 text-slate-800 dark:text-slate-100">
                {[record.start_date || record.startDate, record.end_date || record.endDate].filter(Boolean).join(" ~ ") || "—"}
              </dd>
            </div>
            <div className="md:col-span-2">
              <dt className="text-xs text-slate-500 dark:text-slate-400">试验说明</dt>
              <dd className="mt-0.5 whitespace-pre-wrap text-slate-800 dark:text-slate-100">
                {record.trial_description || record.trialDescription || "—"}
              </dd>
            </div>
          </dl>
        ) : (
          <p className="text-sm text-slate-400">未找到试验数据</p>
        )}
      </div>

      <div className="mb-5 rounded-xl border border-slate-200 bg-white dark:border-slate-800 dark:bg-slate-950">
        <div className="border-b border-slate-200 px-4 py-3 dark:border-slate-800">
          <h3 className="text-sm font-semibold text-slate-900 dark:text-slate-50">联系人 (trial_contact)</h3>
        </div>
        <Table>
          <TableHeader>
            <TableRow className="bg-slate-50 dark:bg-slate-900">
              <TableHead className="text-xs">Person DbId</TableHead>
              <TableHead className="text-xs">姓名</TableHead>
              <TableHead className="text-xs">邮箱</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {contacts.length === 0 ? (
              <TableRow>
                <TableCell colSpan={3} className="py-8 text-center text-sm text-slate-400">暂无联系人</TableCell>
              </TableRow>
            ) : (
              contacts.map((contact) => (
                <TableRow key={contact.contactDbId}>
                  <TableCell className="text-sm">{contact.contactDbId}</TableCell>
                  <TableCell className="text-sm">{contact.name || "—"}</TableCell>
                  <TableCell className="text-sm">{contact.email || "—"}</TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      <div className="rounded-xl border border-slate-200 bg-white dark:border-slate-800 dark:bg-slate-950">
        <div className="border-b border-slate-200 px-4 py-3 dark:border-slate-800">
          <h3 className="text-sm font-semibold text-slate-900 dark:text-slate-50">出版物 (trial_publication)</h3>
        </div>
        <Table>
          <TableHeader>
            <TableRow className="bg-slate-50 dark:bg-slate-900">
              <TableHead className="text-xs">出版物 PUI</TableHead>
              <TableHead className="text-xs">引用 / URL</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {publications.length === 0 ? (
              <TableRow>
                <TableCell colSpan={2} className="py-8 text-center text-sm text-slate-400">暂无出版物</TableCell>
              </TableRow>
            ) : (
              publications.map((publication, index) => (
                <TableRow key={`${publication.publicationPUI}-${index}`}>
                  <TableCell className="text-sm">{publication.publicationPUI || "—"}</TableCell>
                  <TableCell className="break-all text-sm">{publication.publicationReference || "—"}</TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {record ? (
        <TrialMetaDialog
          open={editOpen}
          record={record}
          cropOptions={cropOptions}
          programOptions={programOptions}
          personOptions={personOptions}
          onOpenChange={setEditOpen}
          onSaved={(next) => {
            setRecord(next);
            setEditOpen(false);
          }}
        />
      ) : null}
    </div>
  );
}
