import { useState, useEffect } from 'react';
import axios from 'axios';
import { Users, CheckCircle, XCircle, Shield, Trash2 } from 'lucide-react';

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000';

function AdminDashboard({ token }) {
    const [users, setUsers] = useState([]);
    const [plates, setPlates] = useState([]);
    const [newUser, setNewUser] = useState({ username: '', password: '', role: 'USER' });
    const [activeTab, setActiveTab] = useState('plates'); // 'plates' | 'users'

    useEffect(() => {
        fetchData();
    }, [token]);

    const fetchData = async () => {
        try {
            const authHeader = { headers: { Authorization: `Bearer ${token}` } };
            const [usersRes, platesRes] = await Promise.all([
                axios.get(`${API_URL}/api/auth`, authHeader).catch(err => ({ data: [] })),
                axios.get(`${API_URL}/api/plates`, authHeader)
            ]);
            setUsers(usersRes.data);
            setPlates(platesRes.data);
        } catch (err) {
            console.error(err);
        }
    };

    const handleCreateUser = async (e) => {
        e.preventDefault();
        try {
            await axios.post(`${API_URL}/api/auth/register`, newUser, {
                headers: { Authorization: `Bearer ${token}` }
            });
            setNewUser({ username: '', password: '', role: 'USER' });
            fetchData();
            alert('User created');
        } catch (err) {
            alert('Error: ' + err.message);
        }
    };

    const handleDeleteUser = async (id) => {
        if (!confirm('Area you sure?')) return;
        try {
            await axios.delete(`${API_URL}/api/auth/${id}`, {
                headers: { Authorization: `Bearer ${token}` }
            });
            fetchData();
        } catch (err) {
            console.error(err);
        }
    };

    const handleApprovePlate = async (id, status) => {
        try {
            await axios.put(`${API_URL}/api/plates/${id}/approve`, { status }, {
                headers: { Authorization: `Bearer ${token}` }
            });
            fetchData();
        } catch (err) {
            console.error(err);
        }
    };

    return (
        <div className="min-h-screen bg-slate-900 text-slate-100 p-8">
            <div className="max-w-7xl mx-auto space-y-8">
                <header className="flex items-center justify-between">
                    <h1 className="text-3xl font-bold flex items-center gap-3">
                        <Shield className="text-purple-500" />
                        Admin Portal
                    </h1>
                    <div className="flex bg-slate-800 rounded-lg p-1">
                        <button
                            onClick={() => setActiveTab('plates')}
                            className={`px-4 py-2 rounded-md transition-all ${activeTab === 'plates' ? 'bg-purple-600' : 'hover:text-purple-400'}`}
                        >
                            Plate Approvals
                        </button>
                        <button
                            onClick={() => setActiveTab('users')}
                            className={`px-4 py-2 rounded-md transition-all ${activeTab === 'users' ? 'bg-purple-600' : 'hover:text-purple-400'}`}
                        >
                            User Management
                        </button>
                    </div>
                </header>

                {activeTab === 'plates' && (
                    <div className="bg-slate-800 rounded-2xl p-6 border border-slate-700">
                        <h2 className="text-xl font-semibold mb-6">Pending Approvals</h2>
                        <div className="space-y-4">
                            {plates.filter(p => p.status === 'PENDING').length === 0 && (
                                <p className="text-slate-500">No pending plates.</p>
                            )}
                            {plates.filter(p => p.status === 'PENDING').map(plate => (
                                <div key={plate.id} className="flex items-center justify-between p-4 bg-slate-900 rounded-xl border border-slate-700">
                                    <div>
                                        <div className="font-mono text-xl font-bold">{plate.number}</div>
                                        <div className="text-sm text-slate-400">Owner: {plate.owner} | Added by: {plate.addedBy?.username || 'Unknown'}</div>
                                    </div>
                                    <div className="flex gap-2">
                                        <button
                                            onClick={() => handleApprovePlate(plate.id, 'ALLOWED')}
                                            className="px-4 py-2 bg-green-600 hover:bg-green-500 rounded-lg text-sm font-bold flex items-center gap-2"
                                        >
                                            <CheckCircle size={16} /> Approve
                                        </button>
                                        <button
                                            onClick={() => handleApprovePlate(plate.id, 'DENIED')}
                                            className="px-4 py-2 bg-red-600 hover:bg-red-500 rounded-lg text-sm font-bold flex items-center gap-2"
                                        >
                                            <XCircle size={16} /> Deny
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>

                        <h2 className="text-xl font-semibold mt-10 mb-6">All Plates</h2>
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            {plates.filter(p => p.status !== 'PENDING').map(plate => (
                                <div key={plate.id} className="p-4 bg-slate-900 rounded-xl border border-slate-700 opacity-75 hover:opacity-100 transition-opacity">
                                    <div className="flex justify-between items-start">
                                        <div>
                                            <div className="font-mono text-lg font-bold">{plate.number}</div>
                                            <div className="text-xs text-slate-500">{plate.owner}</div>
                                        </div>
                                        <span className={`text-xs px-2 py-1 rounded ${plate.status === 'ALLOWED' ? 'bg-green-900 text-green-300' : 'bg-red-900 text-red-300'}`}>
                                            {plate.status}
                                        </span>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {activeTab === 'users' && (
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
                        <div className="bg-slate-800 rounded-2xl p-6 border border-slate-700">
                            <h3 className="text-xl font-bold mb-4">Create User</h3>
                            <form onSubmit={handleCreateUser} className="space-y-4">
                                <input
                                    className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3"
                                    placeholder="Username"
                                    value={newUser.username}
                                    onChange={e => setNewUser({ ...newUser, username: e.target.value })}
                                />
                                <input
                                    className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3"
                                    type="password"
                                    placeholder="Password"
                                    value={newUser.password}
                                    onChange={e => setNewUser({ ...newUser, password: e.target.value })}
                                />
                                <select
                                    className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3"
                                    value={newUser.role}
                                    onChange={e => setNewUser({ ...newUser, role: e.target.value })}
                                >
                                    <option value="USER">User</option>
                                    <option value="ADMIN">Admin</option>
                                </select>
                                <button className="w-full py-3 bg-purple-600 hover:bg-purple-500 rounded-lg font-bold">Create User</button>
                            </form>
                        </div>

                        <div className="md:col-span-2 bg-slate-800 rounded-2xl p-6 border border-slate-700">
                            <h3 className="text-xl font-bold mb-4">Existing Users</h3>
                            <div className="space-y-3">
                                {users.map(u => (
                                    <div key={u.id} className="flex items-center justify-between p-4 bg-slate-900 rounded-xl">
                                        <div className="flex items-center gap-4">
                                            <div className="w-10 h-10 bg-slate-700 rounded-full flex items-center justify-center font-bold">
                                                {u.username[0].toUpperCase()}
                                            </div>
                                            <div>
                                                <div className="font-bold">{u.username}</div>
                                                <div className="text-xs text-slate-500">{u.role}</div>
                                            </div>
                                        </div>
                                        {u.username !== 'admin' && (
                                            <button onClick={() => handleDeleteUser(u.id)} className="text-red-400 hover:text-red-300">
                                                <Trash2 size={20} />
                                            </button>
                                        )}
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}

export default AdminDashboard;
