import { useState, useEffect } from "react";
import { adminFetch } from "./adminApi";
import { useToast } from "./Toast";
import { copyItemLink } from "./utils";
import ArticleForm from "./ArticleForm";
import QRCodeModal from "./QRCodeModal";
import PageHeader, {
  PrimaryButton,
  StatusChip,
  ActionButton,
  EmptyState,
  LoadingBlock,
  IconEdit,
  IconCopy,
  IconQR,
  IconDelete,
} from "./PageHeader";
import { TableCard, TableHeadRow } from "./StampList";

type Article = {
  id: string;
  title: string;
  subtitle: string | null;
  coverImage: string;
  sortOrder: number;
  enabled: boolean;
};

export default function ArticleList() {
  const toast = useToast();
  const [articles, setArticles] = useState<Article[]>([]);
  const [loading, setLoading] = useState(true);

  const [formState, setFormState] = useState<{ open: boolean; id: string | null }>({ open: false, id: null });
  const [qrState, setQrState] = useState<{ open: boolean; id: string | null }>({ open: false, id: null });

  const fetchArticles = async () => {
    try {
      const data = await adminFetch<Article[]>("/articles");
      setArticles(data);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchArticles();
  }, []);

  const handleDelete = async (id: string, title: string) => {
    if (!confirm(`确定删除文章「${title}」？`)) return;
    try {
      await adminFetch(`/articles/${id}`, { method: "DELETE" });
      toast.show("已删除");
      fetchArticles();
    } catch (e) {
      toast.show(e instanceof Error ? e.message : "删除失败", "error");
    }
  };

  const handleToggle = async (id: string, enabled: boolean) => {
    await adminFetch(`/articles/${id}`, {
      method: "PUT",
      body: JSON.stringify({ enabled: !enabled }),
    });
    fetchArticles();
  };

  const handleCopyLink = async (id: string) => {
    try {
      await copyItemLink("article", id);
      toast.show("链接已复制");
    } catch {
      toast.show("复制失败", "error");
    }
  };

  return (
    <>
      <PageHeader
        eyebrow="03 · Articles"
        title="文章管理"
        caption="静态文章与对应点位的 NFC 链接"
        action={<PrimaryButton onClick={() => setFormState({ open: true, id: null })}>添加文章</PrimaryButton>}
      />

      {loading ? (
        <LoadingBlock />
      ) : (
        <TableCard>
          {articles.length === 0 ? (
            <EmptyState
              message="尚未创建文章"
              action={
                <PrimaryButton onClick={() => setFormState({ open: true, id: null })}>
                  添加第一篇文章
                </PrimaryButton>
              }
            />
          ) : (
            <table className="w-full">
              <thead>
                <TableHeadRow cols={["封面", "标题 · 副标题", "排序", "状态", "操作"]} />
              </thead>
              <tbody>
                {articles.map((article, i) => (
                  <tr
                    key={article.id}
                    className="border-t border-[var(--border-muted)] hover:bg-white/60 transition-colors animate-admin-row"
                    style={{ animationDelay: `${Math.min(i, 12) * 0.03}s` }}
                  >
                    <td className="px-5 py-4 w-[110px]">
                      <div className="w-[72px] h-12 rounded-md bg-[var(--bg-paper)] border border-[var(--border-muted)] overflow-hidden shadow-sm">
                        {article.coverImage ? (
                          <img src={article.coverImage} alt="" className="w-full h-full object-cover" />
                        ) : (
                          <div className="w-full h-full flex items-center justify-center">
                            <span className="text-[9px] tracking-[0.2em] uppercase text-[var(--text-muted)]/60">
                              —
                            </span>
                          </div>
                        )}
                      </div>
                    </td>
                    <td className="px-5 py-4">
                      <p className="text-[15px] font-medium text-[var(--text-primary)]">{article.title}</p>
                      {article.subtitle && (
                        <p className="text-xs text-[var(--text-muted)] mt-0.5 max-w-[360px] truncate">
                          {article.subtitle}
                        </p>
                      )}
                    </td>
                    <td className="px-5 py-4 text-center w-[80px]">
                      <span
                        className="text-[13px] text-[var(--text-secondary)]"
                        style={{ fontFamily: "'Playfair Display', serif" }}
                      >
                        {article.sortOrder}
                      </span>
                    </td>
                    <td className="px-5 py-4 text-center w-[110px]">
                      <StatusChip
                        enabled={article.enabled}
                        onClick={() => handleToggle(article.id, article.enabled)}
                      />
                    </td>
                    <td className="px-5 py-4 w-[180px]">
                      <div className="flex items-center justify-end gap-1">
                        <ActionButton title="编辑" onClick={() => setFormState({ open: true, id: article.id })}>
                          {IconEdit}
                        </ActionButton>
                        <ActionButton title="复制链接" onClick={() => handleCopyLink(article.id)}>
                          {IconCopy}
                        </ActionButton>
                        <ActionButton title="二维码" onClick={() => setQrState({ open: true, id: article.id })}>
                          {IconQR}
                        </ActionButton>
                        <ActionButton
                          title="删除"
                          variant="danger"
                          onClick={() => handleDelete(article.id, article.title)}
                        >
                          {IconDelete}
                        </ActionButton>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </TableCard>
      )}

      <ArticleForm
        open={formState.open}
        id={formState.id}
        onClose={() => setFormState({ open: false, id: null })}
        onSaved={fetchArticles}
      />
      <QRCodeModal
        open={qrState.open}
        type="article"
        id={qrState.id}
        onClose={() => setQrState({ open: false, id: null })}
      />
    </>
  );
}
