"use client";

import { useEffect, useState } from "react";
import { format } from "date-fns";

interface ApiToken {
  id: number;
  name: string;
  token_prefix: string;
  permissions: string[];
  created_at: string;
  last_used_at: string | null;
  expires_at: string | null;
  is_active: boolean;
}

const ALL_PERMISSIONS = [
  { value: "user:read", label: "用户读取" },
  { value: "user:create", label: "用户创建" },
  { value: "user:update", label: "用户更新" },
  { value: "user:delete", label: "用户删除" },
  { value: "role:read", label: "角色读取" },
  { value: "role:create", label: "角色创建" },
  { value: "role:update", label: "角色更新" },
  { value: "role:delete", label: "角色删除" },
  { value: "log:read", label: "日志读取" },
  { value: "session:manage", label: "会话管理" },
  { value: "platform:read", label: "平台读取" },
  { value: "platform:manage", label: "平台管理" },
  { value: "*", label: "全部权限（超级）" },
];

export default function ApiTokensPage() {
  const [tokens, setTokens] = useState<ApiToken[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreate, setShowCreate] = useState(false);
  const [newName, setNewName] = useState("");
  const [newPerms, setNewPerms] = useState<string[]>([]);
  const [newExpiry, setNewExpiry] = useState("");
  const [creating, setCreating] = useState(false);
  const [createdToken, setCreatedToken] = useState("");
  const [createError, setCreateError] = useState("");

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

  function loadTokens() {
    setLoading(true);
    fetch("/api/api-tokens")
      .then((r) => r.json())
      .then((d) => setTokens(d.tokens || []))
      .catch(console.error)
      .finally(() => setLoading(false));
  }

  async function handleCreate() {
    if (!newName.trim()) { setCreateError("名称不能为空"); return; }
    setCreating(true);
    setCreateError("");
    try {
      const body: Record<string, unknown> = { name: newName, permissions: newPerms };
      if (newExpiry) body.expiresInDays = parseInt(newExpiry, 10);
      const res = await fetch("/api/api-tokens", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      const data = await res.json();
      if (!res.ok) { setCreateError(data.error || "创建失败"); return; }
      setCreatedToken(data.token);
      loadTokens();
      setShowCreate(false);
      setNewName("");
      setNewPerms([]);
      setNewExpiry("");
    } catch { setCreateError("创建失败"); }
    finally { setCreating(false); }
  }

  async function handleDelete(t: ApiToken) {
    if (!confirm(`确定删除 Token「${t.name}」吗？`)) return;
    await fetch(`/api/api-tokens/${t.id}`, { method: "DELETE" });
    loadTokens();
  }

  return (
    <div className="admin-content">
      <div className="page-header" style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <h1 className="page-title">API Token</h1>
          <p className="page-subtitle">用于自动化工具的 API 访问凭证（Bearer Token 认证）</p>
        </div>
        <button className="btn btn-primary" onClick={() => setShowCreate(true)}>+ 新建 Token</button>
      </div>

      {/* Token 使用说明 */}
      <div className="card" style={{ marginBottom: "16px", background: "#fafafa" }}>
        <div style={{ fontSize: "13px", color: "#52525b" }}>
          <strong>使用方法：</strong>在请求头中添加 <code>Authorization: Bearer &lt;your-token&gt;</code>。
          API Token 可访问除 Token 管理本身之外的所有 API。
        </div>
      </div>

      <div className="card">
        {loading ? <div className="loading">加载中...</div> : tokens.length === 0 ? (
          <div className="empty-state">
            <div className="empty-state-icon">🔑</div>
            <p>暂无 API Token，点击上方按钮创建</p>
          </div>
        ) : (
          <div className="table-container">
            <table className="data-table">
              <thead>
                <tr>
                  <th>名称</th>
                  <th>前缀</th>
                  <th>权限</th>
                  <th>有效期</th>
                  <th>最后使用</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {tokens.map((t) => (
                  <tr key={t.id}>
                    <td style={{ fontWeight: 500 }}>{t.name}</td>
                    <td><code style={{ fontSize: "11px" }}>{t.token_prefix}***</code></td>
                    <td>
                      <div style={{ display: "flex", flexWrap: "wrap", gap: "4px" }}>
                        {t.permissions.includes("*") ? (
                          <span className="badge badge-success">全部权限</span>
                        ) : t.permissions.length === 0 ? (
                          <span style={{ color: "#737373", fontSize: "12px" }}>无</span>
                        ) : (
                          t.permissions.map((p) => (
                            <span key={p} className="badge badge-neutral" style={{ fontSize: "11px" }}>{p}</span>
                          ))
                        )}
                      </div>
                    </td>
                    <td style={{ fontSize: "13px" }}>
                      {t.expires_at
                        ? new Date(t.expires_at) < new Date()
                          ? <span style={{ color: "#dc2626" }}>已过期</span>
                          : format(new Date(t.expires_at), "yyyy-MM-dd")
                        : "永不过期"}
                    </td>
                    <td style={{ fontSize: "13px" }}>
                      {t.last_used_at
                        ? format(new Date(t.last_used_at), "yyyy-MM-dd HH:mm")
                        : <span style={{ color: "#a3a3a3" }}>未使用</span>}
                    </td>
                    <td>
                      <button className="btn btn-danger btn-sm" onClick={() => handleDelete(t)}>删除</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* 创建 Token 弹窗 */}
      {showCreate && (
        <div className="modal-overlay" onClick={() => { setShowCreate(false); setCreatedToken(""); }}>
          <div className="modal" onClick={(e) => e.stopPropagation()} style={{ maxWidth: "520px" }}>
            <h2 className="modal-title">新建 API Token</h2>

            {createdToken ? (
              <>
                <div className="alert alert-success" style={{ marginBottom: "16px" }}>
                  Token 创建成功！请立即复制保存，<strong>关闭后将无法再次查看</strong>。
                </div>
                <div className="form-group">
                  <label className="form-label">您的 API Token</label>
                  <div style={{
                    background: "#f4f4f5", border: "1px solid #e5e5e5",
                    borderRadius: "6px", padding: "12px",
                    fontFamily: "monospace", fontSize: "13px",
                    wordBreak: "break-all", color: "#171717"
                  }}>
                    {createdToken}
                  </div>
                </div>
                <div className="modal-footer">
                  <button className="btn btn-primary" onClick={() => { setCreatedToken(""); setShowCreate(false); }}>关闭</button>
                </div>
              </>
            ) : (
              <>
                {createError && <div className="alert alert-error">{createError}</div>}
                <div className="form-group">
                  <label className="form-label">Token 名称 *</label>
                  <input type="text" className="form-input" value={newName}
                    onChange={(e) => setNewName(e.target.value)} placeholder="例如：CI/CD 自动化脚本" autoFocus />
                </div>
                <div className="form-group">
                  <label className="form-label">权限范围</label>
                  <div className="checkbox-group" style={{ maxHeight: "200px" }}>
                    {ALL_PERMISSIONS.map((p) => (
                      <label key={p.value} className="checkbox-item">
                        <input type="checkbox"
                          checked={newPerms.includes(p.value)}
                          onChange={(e) => {
                            setNewPerms(e.target.checked
                              ? [...newPerms, p.value]
                              : newPerms.filter((x) => x !== p.value));
                          }} />
                        {p.label}
                      </label>
                    ))}
                  </div>
                </div>
                <div className="form-group">
                  <label className="form-label">有效期（天，留空永不过期）</label>
                  <input type="number" className="form-input" min="1"
                    value={newExpiry} onChange={(e) => setNewExpiry(e.target.value)}
                    placeholder="不填则永不过期" />
                </div>
                <div className="modal-footer">
                  <button className="btn btn-secondary" onClick={() => setShowCreate(false)}>取消</button>
                  <button className="btn btn-primary" disabled={creating} onClick={handleCreate}>
                    {creating ? "创建中..." : "创建"}
                  </button>
                </div>
              </>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
