"use client";

import { useEffect, useState, FormEvent } from "react";

interface Permission {
  id: number; name: string; code: string; description: string | null; created_at: string;
}

export default function PermissionsPage() {
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreate, setShowCreate] = useState(false);
  const [form, setForm] = useState({ name: "", code: "", description: "" });
  const [error, setError] = useState("");

  useEffect(() => { loadPermissions(); }, []);
  async function loadPermissions() {
    setLoading(true);
    const res = await fetch("/api/permissions");
    const data = await res.json();
    setPermissions(data.permissions || []);
    setLoading(false);
  }

  async function handleCreate(e: FormEvent) {
    e.preventDefault();
    setError("");
    const res = await fetch("/api/permissions", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(form) });
    const data = await res.json();
    if (!res.ok) { setError(data.error || "创建失败"); return; }
    setShowCreate(false);
    setForm({ name: "", code: "", description: "" });
    loadPermissions();
  }

  async function handleDelete(perm: Permission) {
    if (!confirm(`删除权限 "${perm.name}" 吗？`)) return;
    await fetch(`/api/permissions?id=${perm.id}`, { method: "DELETE" });
    loadPermissions();
  }

  return (
    <div className="admin-content">
      <div className="page-header" style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div><h1 className="page-title">权限管理</h1><p className="page-subtitle">共 {permissions.length} 个权限</p></div>
        <button className="btn btn-primary" onClick={() => setShowCreate(true)}>+ 新建权限</button>
      </div>
      <div className="card">
        {loading ? <div className="loading">加载中...</div> : (
          <div className="table-container">
            <table className="data-table">
              <thead><tr><th>ID</th><th>名称</th><th>代码</th><th>描述</th><th>操作</th></tr></thead>
              <tbody>
                {permissions.map((p) => (
                  <tr key={p.id}>
                    <td>{p.id}</td><td>{p.name}</td>
                    <td><code style={{ background: "#f4f4f5", padding: "2px 6px", borderRadius: "4px", fontSize: "12px" }}>{p.code}</code></td>
                    <td>{p.description || "-"}</td>
                    <td><button className="btn btn-danger btn-sm" onClick={() => handleDelete(p)}>删除</button></td>
                  </tr>
                ))}
                {permissions.length === 0 && <tr><td colSpan={5} style={{ textAlign: "center", padding: "24px", color: "#737373" }}>暂无数据</td></tr>}
              </tbody>
            </table>
          </div>
        )}
      </div>
      {showCreate && (
        <div className="modal-overlay" onClick={() => setShowCreate(false)}>
          <div className="modal" onClick={(e) => e.stopPropagation()}>
            <h2 className="modal-title">新建权限</h2>
            {error && <div className="alert alert-error">{error}</div>}
            <form onSubmit={handleCreate}>
              <div className="form-group"><label className="form-label">名称</label>
                <input type="text" className="form-input" value={form.name}
                  onChange={(e) => setForm({ ...form, name: e.target.value })} required /></div>
              <div className="form-group"><label className="form-label">代码 (唯一)</label>
                <input type="text" className="form-input" placeholder="如: user:read" value={form.code}
                  onChange={(e) => setForm({ ...form, code: e.target.value.toLowerCase().replace(/[^a-z0-9_:]/g, "") })} required /></div>
              <div className="form-group"><label className="form-label">描述</label>
                <input type="text" className="form-input" value={form.description}
                  onChange={(e) => setForm({ ...form, description: e.target.value })} /></div>
              <div className="modal-footer">
                <button type="button" className="btn btn-secondary" onClick={() => setShowCreate(false)}>取消</button>
                <button type="submit" className="btn btn-primary">创建</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
