"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { ArrowLeft, List, Pencil } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { fetchListDetail, fetchPersonOptions } from "../api";
import { ListItemPanel } from "../components/ListItemPanel";
import { ListMetaDialog } from "../components/ListMetaDialog";
import { listTypeLabel, type ListRecord, type SelectOption } from "../types";

function formatTimestamp(value: string | null | undefined) {
  if (!value) return "—";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return date.toLocaleString();
}

export default function ListDetailPage() {
  const params = useParams<{ listDbId: string }>();
  const listDbId = decodeURIComponent(params.listDbId ?? "");
  const [record, setRecord] = useState<ListRecord | null>(null);
  const [personOptions, setPersonOptions] = useState<SelectOption[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [editOpen, setEditOpen] = useState(false);

  const loadDetail = useCallback(async () => {
    if (!listDbId) return;
    setLoading(true);
    setError(null);
    try {
      const [people, detail] = await Promise.all([fetchPersonOptions(), fetchListDetail(listDbId)]);
      setPersonOptions(people);
      setRecord(detail);
    } catch (event) {
      setError(event instanceof Error ? event.message : "加载失败");
      setRecord(null);
    } finally {
      setLoading(false);
    }
  }, [listDbId]);

  useEffect(() => {
    let mounted = true;
    loadDetail().catch(() => undefined);
    return () => {
      mounted = false;
    };
  }, [loadDetail]);

  const handleItemsChange = useCallback((items: string[]) => {
    setRecord((current) => (current ? { ...current, data: items, listSize: items.length } : current));
  }, []);

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

  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="/basic-dictionary/base/list" 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-violet-500 to-purple-600 p-2.5">
              <List className="h-5 w-5 text-white" />
            </div>
            <div>
              <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-50">
                {record?.listName || "List 详情"}
              </h2>
              <p className="mt-0.5 text-sm text-slate-500 dark:text-slate-400">
                维护列表基本信息与 list_item 明细
              </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.id}</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">{listTypeLabel(record.listType)}</dd>
            </div>
            <div>
              <dt className="text-xs text-slate-500 dark:text-slate-400">Owner</dt>
              <dd className="mt-0.5 text-slate-800 dark:text-slate-100">{record.listOwnerName || record.listOwnerPersonDbId || "—"}</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.listSource || "—"}</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">{formatTimestamp(record.dateCreated)}</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">{formatTimestamp(record.dateModified)}</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.listDescription || "—"}</dd>
            </div>
          </dl>
        ) : (
          <p className="text-sm text-slate-400">未找到列表数据</p>
        )}
      </div>

      {record ? (
        <ListItemPanel
          listDbId={listDbId}
          items={record.data ?? []}
          onItemsChange={handleItemsChange}
        />
      ) : null}

      {record ? (
        <ListMetaDialog
          open={editOpen}
          record={record}
          personOptions={personOptions}
          onOpenChange={setEditOpen}
          onSaved={setRecord}
        />
      ) : null}
    </div>
  );
}
