import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { adminFetch } from "./adminApi";

type Stamp = {
  id: string;
  name: string;
  note: string | null;
  imageColor: string;
  imageGrey: string;
  sortOrder: number;
  enabled: boolean;
};

export default function StampList() {
  const [stamps, setStamps] = useState<Stamp[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchStamps = async () => {
    setLoading(true);
    try {
      const data = await adminFetch<Stamp[]>("/stamps");
      setStamps(data);
    } finally {
      setLoading(false);
    }
  };

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

  const handleDelete = async (id: string, name: string) => {
    if (!confirm(`确定删除图章「${name}」？`)) return;
    await adminFetch(`/stamps/${id}`, { method: "DELETE" });
    fetchStamps();
  };

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

  if (loading) return <p className="text-gray-500">加载中...</p>;

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-semibold text-gray-800">图章管理</h2>
        <Link
          to="/admin/stamps/new"
          className="px-4 py-2 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700"
        >
          添加图章
        </Link>
      </div>

      <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 border-b border-gray-200">
            <tr>
              <th className="text-left px-4 py-3 font-medium text-gray-600">图章</th>
              <th className="text-left px-4 py-3 font-medium text-gray-600">名称</th>
              <th className="text-left px-4 py-3 font-medium text-gray-600">备注</th>
              <th className="text-center px-4 py-3 font-medium text-gray-600">排序</th>
              <th className="text-center px-4 py-3 font-medium text-gray-600">状态</th>
              <th className="text-right px-4 py-3 font-medium text-gray-600">操作</th>
            </tr>
          </thead>
          <tbody>
            {stamps.map((stamp) => (
              <tr key={stamp.id} className="border-b border-gray-100 hover:bg-gray-50">
                <td className="px-4 py-3">
                  <div className="w-10 h-10 rounded bg-gray-100 overflow-hidden">
                    {stamp.imageColor && (
                      <img src={stamp.imageColor} alt="" className="w-full h-full object-contain" />
                    )}
                  </div>
                </td>
                <td className="px-4 py-3 text-gray-800">{stamp.name}</td>
                <td className="px-4 py-3 text-gray-500 max-w-[200px] truncate">{stamp.note || "—"}</td>
                <td className="px-4 py-3 text-center text-gray-500">{stamp.sortOrder}</td>
                <td className="px-4 py-3 text-center">
                  <button
                    onClick={() => handleToggle(stamp.id, stamp.enabled)}
                    className={`px-2 py-0.5 rounded text-xs ${
                      stamp.enabled ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-500"
                    }`}
                  >
                    {stamp.enabled ? "启用" : "禁用"}
                  </button>
                </td>
                <td className="px-4 py-3 text-right space-x-2">
                  <Link to={`/admin/stamps/${stamp.id}/edit`} className="text-blue-600 hover:underline">
                    编辑
                  </Link>
                  <Link to={`/admin/stamps/${stamp.id}/qrcode`} className="text-blue-600 hover:underline">
                    二维码
                  </Link>
                  <button onClick={() => handleDelete(stamp.id, stamp.name)} className="text-red-500 hover:underline">
                    删除
                  </button>
                </td>
              </tr>
            ))}
            {stamps.length === 0 && (
              <tr>
                <td colSpan={6} className="px-4 py-8 text-center text-gray-400">
                  暂无图章，点击右上角添加
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
