"use client";

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

interface Permission { id: number; name: string; code: string; }
interface Role {
  id: number; name: string; description: string | null; created_at: string;
  permissions?: Permission[];
}

export default function RolesPage() {
  const [roles, setRoles] = useState<Role[]>([]);
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreate, setShowCreate] = useState(false);
  const [showEdit, setShowEdit] = useState<Role | null>(null);
  const [form, setForm] = useState({ name: "", description: "", permissionIds: [] as number[] });
  const [error, setError] = useState("");

  useEffect(() => { loadData(); }, []);
  async function loadData() {
    const [rolesRes, permsRes] = await Promise.all([fetch("/api/roles"), fetch("/api/permissions")]);
    const [rolesData, permsData] = await Promise.all([rolesRes.json(), permsRes.json()]);
    setRoles(rolesData.roles || []);
    setPermissions(permsData.permissions || []);
    setLoading(false);
  }

  async function openEdit(role: Role) {
    const res = await fetch(`/api/roles/${role.id}`);
    const data = await res.json();
    setShowEdit(data);
    setForm({ name: data.name, description: data.description || "", permissionIds: (data.permissions || []).map((p: Permission) => p.id) });
  }

  async function handleCreate(e: FormEvent) {
    e.preventDefault();
    setError("");
    const res = await fetch("/api/roles", { 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);
    loadData();
  }

  async function handleUpdate(e: FormEvent) {
    e.preventDefault();
    if (!showEdit) return;
    setError("");
    const res = await fetch(`/api/roles/${showEdit.id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(form) });
    const data = await res.json();
    if (!res.ok) { setError(data.error || "更新失败"); return; }
    setShowEdit(null);
    loadData();
  }

  async function handleDelete(role: Role) {
    if (!confirm(`删除角色 "${role.name}" 吗？`)) return;
    await fetch(`/api/roles/${role.id}`, { method: "DELETE" });
    loadData();
  }

  function renderModal(title: string, onSubmit: (e: FormEvent) => void) {
    return (
      <div className="modal-overlay" onClick={() => { setShowCreate(false); setShowEdit(null); }}>
        <div className="modal" onClick={(e) => e.stopPropagation()}>
          <h2 className="modal-title">{title}</h2>
          {error && <div className="alert alert-error">{error}</div>}
          <form onSubmit={onSubmit}>
            <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" value={form.description}
                onChange={(e) => setForm({ ...form, description: e.target.value })} />
            </div>
            <div className="form-group">
              <label className="form-label">权限</label>
              <div className="checkbox-group">
                {permissions.map((p) => (
                  <label key={p.id} className="checkbox-item">
                    <input type="checkbox" checked={form.permissionIds.includes(p.id)}
                      onChange={(e) => {
                        const ids = e.target.checked ? [...form.permissionIds, p.id] : form.permissionIds.filter(id => id !== p.id);
                        setForm({ ...form, permissionIds: ids });
                      }} />
                    <span>{p.name}</span>
                    <span style={{ fontSize: "11px", color: "#737373", marginLeft: "4px" }}>{p.code}</span>
                  </label>
                ))}
              </div>
            </div>
            <div className="modal-footer">
              <button type="button" className="btn btn-secondary" onClick={() => { setShowCreate(false); setShowEdit(null); }}>取消</button>
              <button type="submit" className="btn btn-primary">保存</button>
            </div>
          </form>
        </div>
      </div>
    );
  }

  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">共 {roles.length} 个角色</p></div>
        <button className="btn btn-primary" onClick={() => { setForm({ name: "", description: "", permissionIds: [] }); 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>
                {roles.map((r) => (
                  <tr key={r.id}>
                    <td>{r.id}</td><td>{r.name}</td><td>{r.description || "-"}</td>
                    <td>{new Date(r.created_at).toLocaleDateString()}</td>
                    <td><div style={{ display: "flex", gap: "4px" }}>
                      <button className="btn btn-secondary btn-sm" onClick={() => openEdit(r)}>编辑</button>
                      <button className="btn btn-danger btn-sm" onClick={() => handleDelete(r)}>删除</button>
                    </div></td>
                  </tr>
                ))}
                {roles.length === 0 && <tr><td colSpan={5} style={{ textAlign: "center", padding: "24px", color: "#737373" }}>暂无数据</td></tr>}
              </tbody>
            </table>
          </div>
        )}
      </div>
      {showCreate && renderModal("新建角色", handleCreate)}
      {showEdit && renderModal("编辑角色", handleUpdate)}
    </div>
  );
}
