import React, { useState, useEffect, useCallback } from "react";
import { useApp } from "../store";
import {
  adminStats, adminListUsers, adminCreateUser, adminUpdateUser, adminDeleteUser,
  adminListChats, adminGetAppSettings, adminUpdateAppSettings,
  adminGetPermissionDefaults, adminUpdatePermissionDefaults, adminApplyDefaults,
  adminGetUserPermissions, adminUpdateUserPermissions,
} from "../api";
import {
  Users, MessageSquare, Brain, Database, Shield, Plus, Trash2, Edit, Check, X,
  BarChart3, Settings2, ChevronDown, ChevronRight, ToggleLeft, ToggleRight, UserPlus,
  RefreshCw, Lock, Unlock, Save,
} from "lucide-react";

export default function AdminPage() {
  const { state } = useApp();
  const [tab, setTab] = useState("stats");
  const [stats, setStats] = useState(null);
  const [users, setUsers] = useState([]);
  const [chats, setChats] = useState([]);
  const [appSettings, setAppSettings] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  // Create user form
  const [showCreate, setShowCreate] = useState(false);
  const [newUser, setNewUser] = useState({ username: "", email: "", password: "", role: "user", quota_tokens_monthly: 2000000 });

  // Edit user
  const [editUserId, setEditUserId] = useState(null);
  const [editData, setEditData] = useState({});

  // Permissions
  const [permUserId, setPermUserId] = useState(null);
  const [permData, setPermData] = useState(null);
  const [defaults, setDefaults] = useState(null);

  const token = state.token;

  const load = useCallback(async () => {
    setLoading(true);
    setError("");
    try {
      const [s, u, c, as_] = await Promise.all([
        adminStats(token), adminListUsers(token), adminListChats(token), adminGetAppSettings(token),
      ]);
      setStats(s); setUsers(u); setChats(c); setAppSettings(as_);
    } catch (e) { setError(e.message); } finally { setLoading(false); }
  }, [token]);

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

  function flash(msg) { setSuccess(msg); setTimeout(() => setSuccess(""), 3000); }

  async function toggleRegistration() {
    try {
      const res = await adminUpdateAppSettings(token, { registration_enabled: !appSettings.registration_enabled });
      setAppSettings(res);
      flash(res.registration_enabled ? "Registration ENABLED" : "Registration DISABLED");
    } catch (e) { setError(e.message); }
  }

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

  async function handleUpdateUser(userId) {
    try {
      await adminUpdateUser(token, userId, editData);
      setEditUserId(null); flash("User updated"); load();
    } catch (e) { setError(e.message); }
  }

  async function handleDeleteUser(userId, username) {
    if (!confirm(`Delete user "${username}"? This cannot be undone.`)) return;
    try { await adminDeleteUser(token, userId); flash("User deleted"); load(); } catch (e) { setError(e.message); }
  }

  async function handleToggleActive(userId, currentActive) {
    try { await adminUpdateUser(token, userId, { is_active: !currentActive }); flash("User updated"); load(); } catch (e) { setError(e.message); }
  }

  async function openPermissions(userId) {
    try {
      const [p, d] = await Promise.all([adminGetUserPermissions(token, userId), adminGetPermissionDefaults(token)]);
      setPermUserId(userId); setPermData(p); setDefaults(d);
    } catch (e) { setError(e.message); }
  }

  async function savePermissions() {
    try { await adminUpdateUserPermissions(token, permUserId, permData); setPermUserId(null); flash("Permissions saved"); } catch (e) { setError(e.message); }
  }

  const TABS = [
    { id: "stats", label: "Dashboard", icon: BarChart3 },
    { id: "users", label: "Users", icon: Users },
    { id: "settings", label: "Settings", icon: Settings2 },
  ];

  return (
    <div className="flex-1 flex flex-col min-h-0 bg-anton-bg">
      {/* Header */}
      <div className="border-b border-anton-border bg-anton-surface px-6 py-4">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-xl font-bold text-white flex items-center gap-2"><Shield size={20} className="text-anton-accent" /> Admin Dashboard</h1>
            <p className="text-xs text-anton-muted mt-0.5">Superadmin Control Panel</p>
          </div>
          <button onClick={load} className="text-anton-muted hover:text-white transition p-2 rounded-lg hover:bg-anton-card"><RefreshCw size={16} /></button>
        </div>
        <div className="flex gap-1 mt-4">
          {TABS.map((t) => (
            <button key={t.id} onClick={() => setTab(t.id)}
              className={`flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-medium transition ${tab === t.id ? "bg-anton-accent text-white" : "text-anton-muted hover:text-white hover:bg-anton-card"}`}>
              <t.icon size={14} /> {t.label}
            </button>
          ))}
        </div>
      </div>

      {/* Notifications */}
      {error && <div className="mx-6 mt-3 p-3 bg-red-500/10 border border-red-500/30 rounded-lg text-red-400 text-sm flex items-center justify-between">{error} <button onClick={() => setError("")}><X size={14} /></button></div>}
      {success && <div className="mx-6 mt-3 p-3 bg-green-500/10 border border-green-500/30 rounded-lg text-green-400 text-sm">{success}</div>}

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-6 space-y-6">
        {loading && !stats && <div className="text-center text-anton-muted py-12">Loading...</div>}

        {/* ═══ STATS TAB ═══ */}
        {tab === "stats" && stats && (
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
            {[
              { label: "Users", value: stats.total_users, icon: Users, color: "text-blue-400" },
              { label: "Active", value: stats.active_users, icon: Check, color: "text-green-400" },
              { label: "Chats", value: stats.total_chats, icon: MessageSquare, color: "text-purple-400" },
              { label: "Messages", value: stats.total_messages, icon: MessageSquare, color: "text-cyan-400" },
              { label: "Tokens Used", value: (stats.total_tokens_used / 1000000).toFixed(1) + "M", icon: Brain, color: "text-yellow-400" },
              { label: "Knowledge", value: stats.total_knowledge_bases, icon: Database, color: "text-orange-400" },
            ].map((s, i) => (
              <div key={i} className="bg-anton-card border border-anton-border rounded-xl p-4">
                <div className="flex items-center gap-2 mb-2"><s.icon size={14} className={s.color} /><span className="text-xs text-anton-muted">{s.label}</span></div>
                <div className="text-2xl font-bold text-white">{typeof s.value === "number" ? s.value.toLocaleString() : s.value}</div>
              </div>
            ))}
          </div>
        )}

        {/* ═══ USERS TAB ═══ */}
        {tab === "users" && (
          <>
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-semibold text-white">Users ({users.length})</h2>
              <button onClick={() => setShowCreate(!showCreate)} className="flex items-center gap-1.5 px-4 py-2 bg-anton-accent text-white rounded-lg text-sm hover:opacity-90 transition">
                <Plus size={14} /> Create User
              </button>
            </div>

            {showCreate && (
              <form onSubmit={handleCreateUser} className="bg-anton-card border border-anton-border rounded-xl p-4 space-y-3 animate-fade-in">
                <div className="grid grid-cols-2 gap-3">
                  <input value={newUser.username} onChange={(e) => setNewUser({ ...newUser, username: e.target.value })} placeholder="Username" required
                    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 value={newUser.email} onChange={(e) => setNewUser({ ...newUser, email: e.target.value })} placeholder="Email" required type="email"
                    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 value={newUser.password} onChange={(e) => setNewUser({ ...newUser, password: e.target.value })} placeholder="Password" required type="password"
                    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>
                  </select>
                </div>
                <div className="flex gap-2">
                  <button type="submit" className="px-4 py-2 bg-anton-accent text-white rounded-lg text-sm">Create</button>
                  <button type="button" onClick={() => setShowCreate(false)} className="px-4 py-2 bg-anton-card border border-anton-border text-white rounded-lg text-sm">Cancel</button>
                </div>
              </form>
            )}

            <div className="space-y-2">
              {users.map((u) => (
                <div key={u.id} className="bg-anton-card border border-anton-border rounded-xl p-4 flex items-center gap-4">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="text-white font-medium text-sm">{u.username}</span>
                      <span className={`text-[10px] px-1.5 py-0.5 rounded ${u.role === "superadmin" ? "bg-red-500/20 text-red-400" : u.role === "admin" ? "bg-yellow-500/20 text-yellow-400" : "bg-blue-500/20 text-blue-400"}`}>{u.role}</span>
                      {!u.is_active && <span className="text-[10px] px-1.5 py-0.5 rounded bg-gray-500/20 text-gray-400">disabled</span>}
                    </div>
                    <div className="text-xs text-anton-muted mt-0.5">{u.email} • {u.chat_count} chats • {((u.tokens_used_this_month || 0) / 1000000).toFixed(2)}M / {((u.quota_tokens_monthly || 0) / 1000000).toFixed(0)}M tokens</div>
                  </div>
                  {u.role !== "superadmin" && (
                    <div className="flex items-center gap-1">
                      <button onClick={() => handleToggleActive(u.id, u.is_active)} title={u.is_active ? "Disable" : "Enable"}
                        className="p-1.5 rounded-lg hover:bg-anton-bg transition text-anton-muted hover:text-white">
                        {u.is_active ? <Unlock size={14} /> : <Lock size={14} />}
                      </button>
                      <button onClick={() => openPermissions(u.id)} title="Permissions"
                        className="p-1.5 rounded-lg hover:bg-anton-bg transition text-anton-muted hover:text-purple-400">
                        <Shield size={14} />
                      </button>
                      <button onClick={() => handleDeleteUser(u.id, u.username)} title="Delete"
                        className="p-1.5 rounded-lg hover:bg-anton-bg transition text-anton-muted hover:text-red-400">
                        <Trash2 size={14} />
                      </button>
                    </div>
                  )}
                </div>
              ))}
            </div>

            {/* Permissions Modal */}
            {permUserId && permData && (
              <div className="fixed inset-0 z-50 bg-black/60 flex items-center justify-center p-4" onClick={() => setPermUserId(null)}>
                <div className="bg-anton-card border border-anton-border rounded-2xl p-6 w-full max-w-lg max-h-[80vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
                  <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2"><Shield size={18} className="text-purple-400" /> User Permissions</h3>
                  <div className="space-y-3">
                    {["can_use_web_search", "can_use_ui_design", "can_use_knowledge_base", "can_use_gitlab", "can_use_attachments", "can_export_pptx", "can_export_docx"].map((key) => (
                      <label key={key} className="flex items-center justify-between">
                        <span className="text-sm text-white">{key.replace(/^can_/, "").replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())}</span>
                        <button onClick={() => setPermData({ ...permData, [key]: !permData[key] })}
                          className={`transition ${permData[key] ? "text-green-400" : "text-anton-muted"}`}>
                          {permData[key] ? <ToggleRight size={24} /> : <ToggleLeft size={24} />}
                        </button>
                      </label>
                    ))}
                    <div className="border-t border-anton-border pt-3 space-y-3">
                      <div><label className="text-xs text-anton-muted">Allowed Models</label>
                        <input value={permData.allowed_models || ""} onChange={(e) => setPermData({ ...permData, allowed_models: e.target.value })}
                          className="w-full bg-anton-bg border border-anton-border rounded-lg px-3 py-2 text-white text-sm mt-1 focus:outline-none focus:border-anton-accent" /></div>
                      {["max_tokens_cap", "max_reasoning_budget", "max_chats", "max_messages_per_day", "max_knowledge_bases", "max_documents_per_kb", "max_attachment_size_mb", "max_attachments_per_message"].map((key) => (
                        <div key={key}><label className="text-xs text-anton-muted">{key.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())} {key.includes("max_") && permData[key] === 0 ? "(unlimited)" : ""}</label>
                          <input type="number" value={permData[key] || 0} onChange={(e) => setPermData({ ...permData, [key]: parseInt(e.target.value) || 0 })}
                            className="w-full bg-anton-bg border border-anton-border rounded-lg px-3 py-2 text-white text-sm mt-1 focus:outline-none focus:border-anton-accent" /></div>
                      ))}
                    </div>
                  </div>
                  <div className="flex gap-2 mt-4">
                    <button onClick={savePermissions} className="flex items-center gap-1.5 px-4 py-2 bg-anton-accent text-white rounded-lg text-sm"><Save size={14} /> Save</button>
                    <button onClick={() => setPermUserId(null)} className="px-4 py-2 bg-anton-card border border-anton-border text-white rounded-lg text-sm">Cancel</button>
                  </div>
                </div>
              </div>
            )}
          </>
        )}

        {/* ═══ SETTINGS TAB ═══ */}
        {tab === "settings" && (
          <div className="space-y-6">
            {/* Registration Toggle */}
            <div className="bg-anton-card border border-anton-border rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-1 flex items-center gap-2"><UserPlus size={18} className="text-blue-400" /> User Registration</h3>
              <p className="text-xs text-anton-muted mb-4">Control whether new users can register accounts themselves.</p>
              {appSettings && (
                <div className="flex items-center justify-between bg-anton-bg border border-anton-border rounded-xl p-4">
                  <div>
                    <div className="text-sm text-white font-medium">
                      Registration is {appSettings.registration_enabled ? <span className="text-green-400">ENABLED</span> : <span className="text-red-400">DISABLED</span>}
                    </div>
                    <div className="text-xs text-anton-muted mt-0.5">
                      {appSettings.registration_enabled
                        ? "Anyone can create a new account from the login page."
                        : "Only superadmins can create new user accounts."}
                    </div>
                  </div>
                  <button onClick={toggleRegistration}
                    className={`transition-colors ${appSettings.registration_enabled ? "text-green-400 hover:text-green-300" : "text-anton-muted hover:text-white"}`}>
                    {appSettings.registration_enabled ? <ToggleRight size={36} /> : <ToggleLeft size={36} />}
                  </button>
                </div>
              )}
            </div>

            {/* Recent Chats */}
            <div className="bg-anton-card border border-anton-border rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2"><MessageSquare size={18} className="text-purple-400" /> Recent Chats</h3>
              <div className="space-y-2 max-h-80 overflow-y-auto">
                {chats.slice(0, 50).map((c) => (
                  <div key={c.id} className="flex items-center justify-between bg-anton-bg border border-anton-border rounded-lg p-3">
                    <div className="min-w-0">
                      <div className="text-sm text-white truncate">{c.title}</div>
                      <div className="text-xs text-anton-muted">{c.username} • {c.message_count} msgs</div>
                    </div>
                    <span className="text-[10px] text-anton-muted shrink-0">{new Date(c.updated_at).toLocaleDateString()}</span>
                  </div>
                ))}
                {chats.length === 0 && <div className="text-center text-anton-muted text-sm py-4">No chats yet</div>}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}