import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useAuth } from '../AuthContext';
import { Users, PlusCircle, Shield, ArrowLeft, RefreshCw, Key, DollarSign, BarChart2, Save, Activity } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { Tooltip } from '../components/Tooltip';
import { Layout } from '../components/Layout';
// Simple SVG Bar Chart Component
const AnalyticsChart = ({ data }: { data: any[] }) => {
if (!data || data.length === 0) return
No data available for this period.
;
const maxVal = Math.max(...data.map(d => Math.max(d.revenue, d.usage)), 10); // Prevent zero division
const height = 200;
const barWidth = 40;
const gap = 20;
const width = data.length * (barWidth + gap);
return (
);
};
const AdminDashboard: React.FC = () => {
const { user } = useAuth();
const navigate = useNavigate();
// Tab State
const [activeTab, setActiveTab] = useState<'users' | 'pricing' | 'analytics'>('users');
// Data State
const [users, setUsers] = useState([]);
const [configs, setConfigs] = useState({});
const [analytics, setAnalytics] = useState([]);
// Loading State
const [loading, setLoading] = useState(false);
const [editingConfig, setEditingConfig] = useState(null);
const [configValue, setConfigValue] = useState("");
const [analyticsRange, setAnalyticsRange] = useState("30d");
// NEW: User Management State
const [selectedUser, setSelectedUser] = useState(null);
useEffect(() => {
if (user && user.role !== 'ADMIN') {
navigate('/');
return;
}
fetchData();
}, [user, activeTab, analyticsRange]);
const fetchData = async () => {
setLoading(true);
const token = localStorage.getItem('token');
const headers = { Authorization: `Bearer ${token}` };
try {
if (activeTab === 'users') {
const res = await axios.get('/api/admin/users', { headers });
setUsers(res.data.users);
} else if (activeTab === 'pricing') {
const res = await axios.get('/api/admin/config', { headers });
setConfigs(res.data);
} else if (activeTab === 'analytics') {
const res = await axios.get(`/api/admin/analytics?range=${analyticsRange}`, { headers });
const data = Array.isArray(res.data.analytics) ? res.data.analytics : [];
setAnalytics(data);
}
} catch (err) {
console.error("Fetch Error:", err);
} finally {
setLoading(false);
}
};
const updateConfig = async (key: string) => {
try {
const token = localStorage.getItem('token');
await axios.post('/api/admin/config', { key, value: configValue }, {
headers: { Authorization: `Bearer ${token}` }
});
setConfigs({ ...configs, [key]: configValue });
setEditingConfig(null);
} catch (e) {
alert("Failed to update config");
}
};
const addCredits = async (userId: string, amount: number) => {
try {
const token = localStorage.getItem('token');
await axios.post('/api/admin/credits', { userId, amount }, {
headers: { Authorization: `Bearer ${token}` }
});
fetchData(); // Refresh list to show new balance
if (selectedUser) {
// Update local selected user state immediately for better UX
setSelectedUser((prev: any) => ({ ...prev, credits: prev.credits + amount }));
}
} catch (err) {
alert("Failed to add credits");
}
};
const updateUserRole = async (userId: string, role: string) => {
try {
const token = localStorage.getItem('token');
await axios.post('/api/admin/role', { userId, role }, {
headers: { Authorization: `Bearer ${token}` }
});
fetchData(); // Refresh list
if (selectedUser) {
setSelectedUser((prev: any) => ({ ...prev, role }));
}
} catch (err: any) {
alert(err.response?.data?.error || "Failed to update role");
}
};
return (
{/* Admin Sub-Header */}
Admin Command Center
System management and financial oversight.
{/* --- USERS TAB --- */}
{activeTab === 'users' && (
User Management
| User |
Credits |
P&L (Rev/Cost) |
API Key |
Actions |
{users.map(u => (
|
{u.email}
{u.id}
|
{u.credits} |
+${(u.totalRevenue || 0).toFixed(2)}
-${(u.totalCost || 0).toFixed(4)}
|
{u.apiKey ? Key Active : No Key}
|
|
))}
)}
{/* --- USER MANAGEMENT MODAL --- */}
{selectedUser && (
{/* Header */}
Manage User
{selectedUser.email}
{/* Role Management */}
⚠️ Admins have full access. VIPs get priority queue.
{/* Credit Management */}
{selectedUser.credits}
Add Credits
Deduct
{/* Manual Input */}
)}
{/* --- PRICING TAB --- */}
{activeTab === 'pricing' && (
{Object.entries(configs).map(([key, value]) => (
{key}
System Configuration Key
{editingConfig === key ? (
setConfigValue(e.target.value)}
className="flex-1 bg-stone-50 border border-stone-300 rounded px-2 py-1 text-sm font-mono"
/>
) : (
{String(value)}
)}
))}
)}
{/* --- ANALYTICS TAB --- */}
{activeTab === 'analytics' && (
Financial Performance
Revenue (Stripe/Purchase) vs Cost (Gemini API)
{['24h', '7d', '30d'].map(r => (
))}
)}
);
};
export default AdminDashboard;