import React, { useState, useEffect, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { useApp } from "../store";
import {
  adminStats,
  adminListUsers,
  adminCreateUser,
  adminUpdateUser,
  adminDeleteUser,
} from "../api";
import {
  ArrowLeft, Users, MessageSquare, Database, Zap,
  UserPlus, Trash2, Shield, ShieldOff, Save, X,
} from "lucide-react";

export default function AdminPage() {
  const { state } = useApp();
  const navigate = useNavigate();
  const [stats, setStats] = useState(null);
  const [users, setUsers] = useState([]);
  const [showCreate, setShowCreate] = useState(false);
  const [editId, setEditId] = useState(null);
  const [editData, setEditData] = useState({});
  const [newUser, setNewUser] = useState({
    username: "", email: "", password: "", role: "user", quota_tokens_monthly: 2000000,
  });
  const [error, setError] = useState("");

  const load = useCallback(async () => {
    try {
      const [s, u] = await Promise.all([
        adminStats(state.token),
        adminListUsers(state.token),
      ]);
      setStats(s);
      setUsers(u);
    } catch (err) {
      setError(err.message);
    }
  }, [state.token]);

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

  async function handleCreate(e) {
    e.preventDefault();
    try {
      await adminCreateUser(state.token, newUser);
      setShowCreate(false);
      setNewUser({ username: "", email: "", password: "", role: "user", quota_tokens_monthly: 2000000 });
      load();
    } catch (err) { setError(err.message); }
  }

  async function handleSaveEdit(userId) {
    try {
      await adminUpdateUser(state.token, userId, editData);
      setEditId(null);
      load();
    } catch (err) { setError(err.message); }
  }

  async function handleDelete(userId, username) {
    if (!confirm(`Delete user "${username}"? This is permanent.`)) return;
    try {
      await adminDeleteUser(state.token, userId);
      load();
    } catch (err) { setError(err.message); }
  }

  function formatNum(n) {
    if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + "M";
    if (n >= 1_000) return (n / 1_000).toFixed(0) + "K";
    return String(n);
  }

  if (state.user?.role !== "superadmin") {
    return (
      <div className="h-full flex items-center justify-center">
        <p className="text-anton-danger text-lg">⛔ Access Denied</p>
      </div>
    );
  }

  return (
    <div className="h-full overflow-y-auto bg-anton-bg p-6">
      <div className="max-w-6xl mx-auto space-y-6 animate-fade-in">
        {/* Header */}
        <div className="flex items-center gap-4">
          <button onClick={() => navigate("/")} className="p-2 rounded-lg bg-anton-surface border border-anton-border hover:border-anton-accent transition">
            <ArrowLeft size={20} />
          </button>
          <div>
            <h1 className="text-2xl font-bold text-white flex items-center gap-2">
              <Shield size={24} className="text-anton-accent" /> Admin Panel
            </h1>
            <p className="text-anton-muted text-sm">Manage everything</p>
          </div>
        </div>

        {error && (
          <div className="bg-red-500/10 border border-red-500/30 text-red-400 text-sm rounded-lg p-3">
            {error}
            <button onClick={() => setError("")} className="ml-2 text-red-300 hover:text-white">✕</button>
          </div>
        )}

        {/* Stats */}
        {stats && (
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {[
              { label: "Users", value: stats.total_users, icon: Users, color: "text-blue-400" },
              { label: "Chats", value: stats.total_chats, icon: MessageSquare, color: "text-green-400" },
              { label: "Messages", value: formatNum(stats.total_messages), icon: Zap, color: "text-anton-accent" },
              { label: "Tokens Used", value: formatNum(stats.total_tokens_used), icon: Database, color: "text-purple-400" },
            ].map((s) => (
              <div key={s.label} className="bg-anton-surface border border-anton-border rounded-xl p-4">
                <div className="flex items-center gap-2 mb-1">
                  <s.icon size={16} className={s.color} />
                  <span className="text-anton-muted text-sm">{s.label}</span>
                </div>
                <p className="text-2xl font-bold text-white">{s.value}</p>
              </div>
            ))}
          </div>
        )}

        {/* User Management */}
        <div className="bg-anton-surface border border-anton-border rounded-xl overflow-hidden">
          <div className="px-5 py-4 border-b border-anton-border flex items-center justify-between">
            <h2 className="text-lg font-semibold text-white">Users</h2>
            <button
              onClick={() => setShowCreate(!showCreate)}
              className="flex items-center gap-1.5 px-3 py-1.5 bg-anton-accent text-white rounded-lg text-sm font-medium hover:opacity-90 transition"
            >
              {showCreate ? <X size={14} /> : <UserPlus size={14} />}
              {showCreate ? "Cancel" : "New User"}
            </button>
          </div>

          {showCreate && (
            <form onSubmit={handleCreate} className="px-5 py-4 border-b border-anton-border bg-anton-card grid grid-cols-1 md:grid-cols-3 gap-3">
              <input placeholder="Username" required value={newUser.username}
                onChange={(e) => setNewUser({ ...newUser, username: e.target.value })}
                className="bg-anton-bg border border-anton-border rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-anton-accent"
              />
              <input placeholder="Email" type="email" required value={newUser.email}
                onChange={(e) => setNewUser({ ...newUser, email: e.target.value })}
                className="bg-anton-bg border border-anton-border rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-anton-accent"
              />
              <input placeholder="Password" required value={newUser.password}
                onChange={(e) => setNewUser({ ...newUser, password: e.target.value })}
                className="bg-anton-bg border border-anton-border rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-anton-accent"
              />
              <select value={newUser.role}
                onChange={(e) => setNewUser({ ...newUser, role: e.target.value })}
                className="bg-anton-bg border border-anton-border rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-anton-accent"
              >
                <option value="user">User</option>
                <option value="admin">Admin</option>
                <option value="superadmin">Superadmin</option>
              </select>
              <input placeholder="Monthly quota" type="number" value={newUser.quota_tokens_monthly}
                onChange={(e) => setNewUser({ ...newUser, quota_tokens_monthly: Number(e.target.value) })}
                className="bg-anton-bg border border-anton-border rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-anton-accent"
              />
              <button type="submit" className="bg-anton-success text-white rounded-lg px-3 py-2 text-sm font-medium hover:opacity-90">
                Create
              </button>
            </form>
          )}

          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left text-anton-muted border-b border-anton-border">
                  <th className="px-5 py-3">User</th>
                  <th className="px-5 py-3">Role</th>
                  <th className="px-5 py-3">Quota</th>
                  <th className="px-5 py-3">Used</th>
                  <th className="px-5 py-3">Chats</th>
                  <th className="px-5 py-3">Status</th>
                  <th className="px-5 py-3">Actions</th>
                </tr>
              </thead>
              <tbody>
                {users.map((u) => (
                  <tr key={u.id} className="border-b border-anton-border/50 hover:bg-anton-card/50 transition">
                    <td className="px-5 py-3">
                      <div className="text-white font-medium">{u.username}</div>
                      <div className="text-anton-muted text-xs">{u.email}</div>
                    </td>
                    <td className="px-5 py-3">
                      {editId === u.id ? (
                        <select value={editData.role ?? u.role}
                          onChange={(e) => setEditData({ ...editData, role: e.target.value })}
                          className="bg-anton-bg border border-anton-border rounded px-2 py-1 text-white text-xs"
                        >
                          <option value="user">user</option>
                          <option value="admin">admin</option>
                          <option value="superadmin">superadmin</option>
                        </select>
                      ) : (
                        <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${
                          u.role === "superadmin" ? "bg-anton-accent/20 text-anton-accent"
                          : u.role === "admin" ? "bg-blue-500/20 text-blue-400"
                          : "bg-anton-border text-anton-muted"
                        }`}>
                          {u.role}
                        </span>
                      )}
                    </td>
                    <td className="px-5 py-3 text-anton-muted">
                      {editId === u.id ? (
                        <input type="number" value={editData.quota_tokens_monthly ?? u.quota_tokens_monthly}
                          onChange={(e) => setEditData({ ...editData, quota_tokens_monthly: Number(e.target.value) })}
                          className="bg-anton-bg border border-anton-border rounded px-2 py-1 text-white text-xs w-28"
                        />
                      ) : formatNum(u.quota_tokens_monthly)}
                    </td>
                    <td className="px-5 py-3 text-anton-muted">
                      {formatNum(u.tokens_used_this_month)}
                    </td>
                    <td className="px-5 py-3 text-anton-muted">{u.chat_count}</td>
                    <td className="px-5 py-3">
                      <span className={`w-2 h-2 inline-block rounded-full mr-1 ${u.is_active ? "bg-anton-success" : "bg-anton-danger"}`} />
                      <span className="text-xs text-anton-muted">{u.is_active ? "Active" : "Disabled"}</span>
                    </td>
                    <td className="px-5 py-3">
                      <div className="flex items-center gap-1">
                        {editId === u.id ? (
                          <>
                            <button onClick={() => handleSaveEdit(u.id)} className="p-1 rounded hover:bg-anton-success/20 text-anton-success"><Save size={14} /></button>
                            <button onClick={() => setEditId(null)} className="p-1 rounded hover:bg-anton-border text-anton-muted"><X size={14} /></button>
                          </>
                        ) : (
                          <>
                            <button onClick={() => { setEditId(u.id); setEditData({}); }}
                              className="p-1 rounded hover:bg-anton-accent/20 text-anton-accent text-xs">Edit</button>
                            <button onClick={() => adminUpdateUser(state.token, u.id, { is_active: !u.is_active }).then(load)}
                              className="p-1 rounded hover:bg-anton-border text-anton-muted"
                              title={u.is_active ? "Disable" : "Enable"}>
                              {u.is_active ? <ShieldOff size={14} /> : <Shield size={14} />}
                            </button>
                            {u.role !== "superadmin" && (
                              <button onClick={() => handleDelete(u.id, u.username)}
                                className="p-1 rounded hover:bg-red-500/20 text-anton-danger"><Trash2 size={14} /></button>
                            )}
                          </>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}