"use client";

import { useEffect, useState, FormEvent } from "react";
import Link from "next/link";

interface AdminUser {
  id: number;
  username: string;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

interface Role {
  id: number;
  name: string;
}

export default function AdminUsersPage() {
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);
  const [showCreate, setShowCreate] = useState(false);
  const [createForm, setCreateForm] = useState({ username: "", password: "", roleIds: [] as number[] });
  const [roles, setRoles] = useState<Role[]>([]);
  const [error, setError] = useState("");

  const pageSize = 20;

  useEffect(() => { loadUsers(); }, [page, search]);
  useEffect(() => {
    fetch("/api/roles")
      .then((r) => r.json())
      .then((data) => setRoles(data.roles || []))
      .catch(console.error);
  }, []);

  async function loadUsers() {
    setLoading(true);
    const params = new URLSearchParams({ page: String(page), pageSize: String(pageSize) });
    if (search) params.set("search", search);
    const res = await fetch(`/api/users?${params}`);
    if (res.status === 401) {
      window.location.href = "/login";
      return;
    }
    const data = await res.json();
    setUsers(data.users || []);
    setTotal(data.total || 0);
    setLoading(false);
  }

  async function handleCreate(e: FormEvent) {
    e.preventDefault();
    setError("");
    const res = await fetch("/api/users", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(createForm),
    });
    const data = await res.json();
    if (!res.ok) { setError(data.error || "创建失败"); return; }
    setShowCreate(false);
    setCreateForm({ username: "", password: "", roleIds: [] });
    loadUsers();
  }

  async function handleToggleActive(u: AdminUser) {
    await fetch(`/api/users/${u.id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ isActive: !u.is_active }),
    });
    loadUsers();
  }

  async function handleDelete(u: AdminUser) {
    if (!confirm(`确定删除 "${u.username}" 吗？`)) return;
    await fetch(`/api/users/${u.id}`, { method: "DELETE" });
    loadUsers();
  }

  const totalPages = Math.ceil(total / pageSize);

  return (
    <div className="admin-content">
      <div className="page-header" style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <h1 className="page-title">Admin 用户管理</h1>
          <p className="page-subtitle">共 {total} 个管理员用户</p>
        </div>
        <button className="btn btn-primary" onClick={() => setShowCreate(true)}>+ 新建用户</button>
      </div>

      <div className="toolbar">
        <input type="text" className="form-input search-input" placeholder="搜索用户名..." value={search}
          onChange={(e) => { setSearch(e.target.value); setPage(1); }} />
      </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>
                {users.map((u) => (
                  <tr key={u.id}>
                    <td>{u.id}</td>
                    <td>{u.username}</td>
                    <td><span className={`badge ${u.is_active ? "badge-success" : "badge-danger"}`}>{u.is_active ? "启用" : "禁用"}</span></td>
                    <td>{new Date(u.created_at).toLocaleDateString()}</td>
                    <td>
                      <div style={{ display: "flex", gap: "4px" }}>
                        <Link href={`/admin/users/${u.id}`}><button className="btn btn-secondary btn-sm">详情</button></Link>
                        <button className="btn btn-secondary btn-sm" onClick={() => handleToggleActive(u)}>{u.is_active ? "禁用" : "启用"}</button>
                        <button className="btn btn-danger btn-sm" onClick={() => handleDelete(u)}>删除</button>
                      </div>
                    </td>
                  </tr>
                ))}
                {users.length === 0 && (
                  <tr><td colSpan={5} style={{ textAlign: "center", padding: "24px", color: "#737373" }}>暂无数据</td></tr>
                )}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {totalPages > 1 && (
        <div className="pagination">
          <span className="pagination-info">第 {page} / {totalPages} 页，共 {total} 条</span>
          <button className="btn btn-secondary btn-sm" disabled={page <= 1} onClick={() => setPage(p => p - 1)}>上一页</button>
          <button className="btn btn-secondary btn-sm" disabled={page >= totalPages} onClick={() => setPage(p => p + 1)}>下一页</button>
        </div>
      )}

      {showCreate && (
        <div className="modal-overlay" onClick={() => setShowCreate(false)}>
          <div className="modal" onClick={(e) => e.stopPropagation()}>
            <h2 className="modal-title">新建 Admin 用户</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={createForm.username}
                  onChange={(e) => setCreateForm({ ...createForm, username: e.target.value })} required />
              </div>
              <div className="form-group">
                <label className="form-label">密码</label>
                <input type="password" className="form-input" value={createForm.password} minLength={6}
                  onChange={(e) => setCreateForm({ ...createForm, password: e.target.value })} required />
              </div>
              <div className="form-group">
                <label className="form-label">角色</label>
                <div className="checkbox-group">
                  {roles.map((r) => (
                    <label key={r.id} className="checkbox-item">
                      <input type="checkbox" checked={createForm.roleIds.includes(r.id)}
                        onChange={(e) => {
                          const ids = e.target.checked ? [...createForm.roleIds, r.id] : createForm.roleIds.filter(id => id !== r.id);
                          setCreateForm({ ...createForm, roleIds: ids });
                        }} />
                      {r.name}
                    </label>
                  ))}
                </div>
              </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>
  );
}
