import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Car, CreditCard, Power, Plus, Trash2, LayoutDashboard, Settings, LogOut, Search, MoreVertical, X, Check } from 'lucide-react';

const AdminDashboard = () => {
    const [vehicles, setVehicles] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [showAddModal, setShowAddModal] = useState(false);
    const [editingId, setEditingId] = useState(null);
    const [newCar, setNewCar] = useState({
        name: '', type: 'SEDAN', seats: '4+1', luggage: '2 Bags', image: 'dzire',
        baseFarePerDay: 2500, driverAllowancePerDay: 400, extraKmRate: 13,
        includedKmPerDay: 300, badge: 'Standard', features: []
    });
    
    const navigate = useNavigate();

    useEffect(() => {
        const token = localStorage.getItem('adminToken');
        if (!token) navigate('/admin/login');
        else fetchVehicles();
    }, []);

    const fetchVehicles = async () => {
        try {
            const res = await fetch('/api/admin/vehicles');
            const data = await res.json();
            setVehicles(data);
        } catch (err) {
            console.error(err);
        } finally {
            setIsLoading(false);
        }
    };

    const toggleAvailability = async (id, currentStatus) => {
        try {
            await fetch(`/api/admin/vehicles/${id}`, {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ isAvailable: !currentStatus })
            });
            fetchVehicles();
        } catch (err) {
            console.error(err);
        }
    };

    const updatePrice = async (id, newPrice) => {
        try {
            await fetch(`/api/admin/vehicles/${id}`, {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ baseFarePerDay: parseInt(newPrice) })
            });
            setEditingId(null);
            fetchVehicles();
        } catch (err) {
            console.error(err);
        }
    };

    const deleteVehicle = async (id) => {
        if (!window.confirm('Delete this vehicle from fleet?')) return;
        try {
            await fetch(`/api/admin/vehicles/${id}`, { method: 'DELETE' });
            fetchVehicles();
        } catch (err) {
            console.error(err);
        }
    };

    const handleAddVehicle = async (e) => {
        e.preventDefault();
        try {
            await fetch('/api/admin/vehicles', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(newCar)
            });
            setShowAddModal(false);
            fetchVehicles();
        } catch (err) {
            console.error(err);
        }
    };

    const logout = () => {
        localStorage.removeItem('adminToken');
        navigate('/admin/login');
    };

    return (
        <div className="min-h-screen bg-[#f8fafc] flex">
            {/* Sidebar */}
            <div className="w-64 bg-slate-900 text-white flex flex-col">
                <div className="p-6 border-b border-white/10">
                    <h1 className="text-xl font-bold flex items-center gap-2">
                        <div className="w-8 h-8 bg-indigo-500 rounded-lg flex items-center justify-center">
                            <Car className="w-5 h-5" />
                        </div>
                        road.rentals
                    </h1>
                    <p className="text-slate-400 text-xs mt-1">Admin Panel v2.0</p>
                </div>
                
                <nav className="flex-1 p-4 space-y-2">
                    <button className="w-full flex items-center gap-3 px-4 py-3 bg-indigo-600 rounded-xl text-sm font-semibold text-white">
                        <LayoutDashboard className="w-5 h-5" />
                        Fleet Control
                    </button>
                    <button className="w-full flex items-center gap-3 px-4 py-3 text-slate-400 hover:bg-white/5 rounded-xl text-sm font-semibold transition-all">
                        <CreditCard className="w-5 h-5" />
                        Booking Reports
                    </button>
                    <button className="w-full flex items-center gap-3 px-4 py-3 text-slate-400 hover:bg-white/5 rounded-xl text-sm font-semibold transition-all">
                        <Settings className="w-5 h-5" />
                        System Config
                    </button>
                </nav>

                <div className="p-4 mt-auto">
                    <button 
                        onClick={logout}
                        className="w-full flex items-center gap-3 px-4 py-3 text-red-400 hover:bg-red-500/10 rounded-xl text-sm font-semibold transition-all"
                    >
                        <LogOut className="w-5 h-5" />
                        Logout
                    </button>
                </div>
            </div>

            {/* Main Content */}
            <div className="flex-1 flex flex-col max-h-screen overflow-hidden">
                <header className="bg-white border-b border-slate-200 px-8 py-4 flex items-center justify-between">
                    <div>
                        <h2 className="text-xl font-bold text-slate-800">Fleet Management</h2>
                        <p className="text-sm text-slate-500">Inventory control and dynamic pricing</p>
                    </div>
                    <button 
                        onClick={() => setShowAddModal(true)}
                        className="bg-indigo-600 hover:bg-indigo-700 text-white px-5 py-2.5 rounded-xl text-sm font-bold shadow-lg shadow-indigo-100 flex items-center gap-2 transition-all"
                    >
                        <Plus className="w-5 h-5" />
                        Add New Vehicle
                    </button>
                </header>

                <main className="flex-1 p-8 overflow-y-auto">
                    {/* Stats */}
                    <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
                        <div className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm">
                            <p className="text-sm text-slate-500 font-semibold mb-1">Total Fleet</p>
                            <h3 className="text-28 font-bold text-slate-900">{vehicles.length} Cars</h3>
                        </div>
                        <div className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm">
                            <p className="text-sm text-slate-400 font-semibold mb-1">Active Now</p>
                            <h3 className="text-28 font-bold text-green-600">{vehicles.filter(v => v.isAvailable).length} Cars</h3>
                        </div>
                        <div className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm">
                            <p className="text-sm text-slate-400 font-semibold mb-1">Maintenance</p>
                            <h3 className="text-28 font-bold text-red-500">{vehicles.filter(v => !v.isAvailable).length} Cars</h3>
                        </div>
                        <div className="bg-indigo-600 p-6 rounded-2xl shadow-xl shadow-indigo-100 text-white">
                            <p className="text-sm text-white/70 font-semibold mb-1">Fleet Revenue</p>
                            <h3 className="text-28 font-bold">Dynamic</h3>
                        </div>
                    </div>

                    {/* Table */}
                    <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
                        <table className="w-full text-left border-collapse">
                            <thead>
                                <tr className="bg-slate-50 border-b border-slate-200">
                                    <th className="px-6 py-4 text-xs font-bold text-slate-500 uppercase tracking-wider">Vehicle Details</th>
                                    <th className="px-6 py-4 text-xs font-bold text-slate-500 uppercase tracking-wider">Type / Capacity</th>
                                    <th className="px-6 py-4 text-xs font-bold text-slate-500 uppercase tracking-wider">Base Price / Day</th>
                                    <th className="px-6 py-4 text-xs font-bold text-slate-500 uppercase tracking-wider">Status</th>
                                    <th className="px-6 py-4 text-xs font-bold text-slate-500 uppercase tracking-wider text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-100">
                                {isLoading ? (
                                    <tr><td colSpan="5" className="p-10 text-center text-slate-400">Loading fleet data...</td></tr>
                                ) : vehicles.map(vehicle => (
                                    <tr key={vehicle.id} className="hover:bg-slate-50 transition-colors">
                                        <td className="px-6 py-4">
                                            <div className="flex items-center gap-3">
                                                <div className="w-12 h-12 bg-slate-100 rounded-lg overflow-hidden flex items-center justify-center">
                                                    <Car className="w-6 h-6 text-slate-400" />
                                                </div>
                                                <div>
                                                    <p className="font-bold text-slate-900">{vehicle.name}</p>
                                                    <p className="text-xs text-slate-500">{vehicle.badge || 'Standard'}</p>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-6 py-4">
                                            <span className="text-xs font-bold px-2 py-1 bg-slate-100 rounded-md text-slate-600 mr-2">{vehicle.type}</span>
                                            <span className="text-sm text-slate-500 font-medium">{vehicle.seats} Seater</span>
                                        </td>
                                        <td className="px-6 py-4">
                                            {editingId === vehicle.id ? (
                                                <div className="flex items-center gap-2">
                                                    <input 
                                                        type="number"
                                                        defaultValue={vehicle.baseFarePerDay}
                                                        className="w-20 px-2 py-1 border border-indigo-300 rounded outline-none"
                                                        onKeyDown={(e) => {
                                                            if (e.key === 'Enter') updatePrice(vehicle.id, e.target.value);
                                                            if (e.key === 'Escape') setEditingId(null);
                                                        }}
                                                    />
                                                </div>
                                            ) : (
                                                <div 
                                                    onClick={() => setEditingId(vehicle.id)}
                                                    className="font-bold text-slate-900 cursor-pointer hover:text-indigo-600"
                                                >
                                                    ₹{vehicle.baseFarePerDay}
                                                </div>
                                            )}
                                        </td>
                                        <td className="px-6 py-4">
                                            <button 
                                                onClick={() => toggleAvailability(vehicle.id, vehicle.isAvailable)}
                                                className={`flex items-center gap-2 text-xs font-bold px-3 py-1.5 rounded-full transition-all ${
                                                    vehicle.isAvailable 
                                                    ? 'bg-green-50 text-green-600 border border-green-100 hover:bg-green-100' 
                                                    : 'bg-red-50 text-red-600 border border-red-100 hover:bg-red-100'
                                                }`}
                                            >
                                                <Power className="w-3 h-3" />
                                                {vehicle.isAvailable ? 'AVAILABLE' : 'OFF DUTY'}
                                            </button>
                                        </td>
                                        <td className="px-6 py-4 text-right">
                                            <button 
                                                onClick={() => deleteVehicle(vehicle.id)}
                                                className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-all"
                                            >
                                                <Trash2 className="w-5 h-5" />
                                            </button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </main>
            </div>

            {/* Add Cab Modal */}
            {showAddModal && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/40 backdrop-blur-sm">
                    <div className="bg-white w-full max-w-xl rounded-2xl shadow-2xl overflow-hidden border border-slate-200">
                        <header className="px-8 py-6 bg-slate-50 border-b border-slate-200 flex items-center justify-between">
                            <h3 className="text-xl font-bold text-slate-900">Add New Fleet Vehicle</h3>
                            <button onClick={() => setShowAddModal(false)} className="text-slate-400 hover:text-slate-600">
                                <X className="w-6 h-6" />
                            </button>
                        </header>
                        <form onSubmit={handleAddVehicle} className="p-8 space-y-6">
                            <div className="grid grid-cols-2 gap-6">
                                <div>
                                    <label className="block text-sm font-bold text-slate-700 mb-2">Vehicle Name</label>
                                    <input 
                                        required
                                        className="w-full px-4 py-2.5 rounded-xl border border-slate-200 outline-none"
                                        placeholder="e.g. Audi A8 L"
                                        onChange={e => setNewCar({...newCar, name: e.target.value})}
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-bold text-slate-700 mb-2">Category</label>
                                    <select 
                                        className="w-full px-4 py-2.5 rounded-xl border border-slate-200 outline-none"
                                        onChange={e => setNewCar({...newCar, type: e.target.value})}
                                    >
                                        <option value="LUXURY">Luxury</option>
                                        <option value="SUV">SUV</option>
                                        <option value="MUV">MUV</option>
                                        <option value="SEDAN">Sedan</option>
                                        <option value="VAN">Van</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="block text-sm font-bold text-slate-700 mb-2">Seats</label>
                                    <input 
                                        className="w-full px-4 py-2.5 rounded-xl border border-slate-200 outline-none"
                                        placeholder="e.g. 4+1"
                                        onChange={e => setNewCar({...newCar, seats: e.target.value})}
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-bold text-slate-700 mb-2">Base Fare</label>
                                    <input 
                                        type="number"
                                        className="w-full px-4 py-2.5 rounded-xl border border-slate-200 outline-none"
                                        placeholder="₹ per day"
                                        onChange={e => setNewCar({...newCar, baseFarePerDay: parseInt(e.target.value)})}
                                    />
                                </div>
                            </div>
                            <button className="w-full bg-indigo-600 hover:bg-fuchsia-600 text-white font-bold py-4 rounded-xl shadow-lg transition-all">
                                Confirm & Add to Fleet
                            </button>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default AdminDashboard;
