import { useState, useEffect } from 'react';
import axios from 'axios';
import { Car, Clock, CheckCircle, AlertCircle } from 'lucide-react';
import io from 'socket.io-client';

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

function UserDashboard({ token, username }) {
    const [plates, setPlates] = useState([]);
    const [newPlate, setNewPlate] = useState({ number: '', owner: '' });
    const [detections, setDetections] = useState([]);

    useEffect(() => {
        fetchPlates();

        // Listen for live detections (optional, maybe user wants to see their plates detected?)
        // For now, let's show all global detections but emphasize this is a "Portal"
        socket.on('new_detection', (data) => {
            setDetections(prev => [data, ...prev].slice(0, 5));
        });

        return () => socket.off('new_detection');
    }, [token]);

    const fetchPlates = async () => {
        try {
            const res = await axios.get(`${API_URL}/api/plates`, {
                headers: { Authorization: `Bearer ${token}` }
            });
            // Filter plates added by this user (if backend doesn't filter, we filter here)
            // Note: Backend currently returns ALL plates. We can filter on client for now.
            const myPlates = res.data.filter(p => p.addedBy?.username === username);
            setPlates(myPlates);
        } catch (err) {
            console.error(err);
        }
    };

    const handleRegister = async (e) => {
        e.preventDefault();
        try {
            await axios.post(`${API_URL}/api/plates`, {
                number: newPlate.number.toUpperCase(),
                owner: newPlate.owner
            }, {
                headers: { Authorization: `Bearer ${token}` }
            });
            setNewPlate({ number: '', owner: '' });
            fetchPlates();
            alert('Plate registered! Waiting for admin approval.');
        } catch (err) {
            alert('Error: ' + err.message);
        }
    };

    return (
        <div className="min-h-screen bg-slate-900 text-slate-100 p-8">
            <div className="max-w-6xl mx-auto grid grid-cols-1 lg:grid-cols-3 gap-8">

                {/* Left: Register & My Plates */}
                <div className="lg:col-span-2 space-y-8">
                    <header>
                        <h1 className="text-3xl font-bold bg-gradient-to-r from-blue-400 to-cyan-300 bg-clip-text text-transparent mb-2">
                            Welcome, {username}
                        </h1>
                        <p className="text-slate-400">Manage your vehicles and access.</p>
                    </header>

                    <div className="bg-slate-800 rounded-2xl p-6 border border-slate-700">
                        <h2 className="text-xl font-semibold mb-6 flex items-center gap-2">
                            <Car className="text-blue-400" /> My Registered Plates
                        </h2>

                        <div className="space-y-4">
                            {plates.length === 0 && <p className="text-slate-500">No plates registered.</p>}
                            {plates.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 tracking-wider">{plate.number}</div>
                                        <div className="text-sm text-slate-400">{plate.owner}</div>
                                    </div>
                                    <div>
                                        {plate.status === 'ALLOWED' && (
                                            <span className="flex items-center gap-1 text-green-400 bg-green-900/30 px-3 py-1 rounded-full text-xs font-bold">
                                                <CheckCircle size={14} /> ACTIVE
                                            </span>
                                        )}
                                        {plate.status === 'PENDING' && (
                                            <span className="flex items-center gap-1 text-yellow-400 bg-yellow-900/30 px-3 py-1 rounded-full text-xs font-bold">
                                                <Clock size={14} /> PENDING
                                            </span>
                                        )}
                                        {plate.status === 'DENIED' && (
                                            <span className="flex items-center gap-1 text-red-400 bg-red-900/30 px-3 py-1 rounded-full text-xs font-bold">
                                                <AlertCircle size={14} /> DENIED
                                            </span>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>

                    <div className="bg-slate-800 rounded-2xl p-6 border border-slate-700">
                        <h2 className="text-xl font-semibold mb-4">Request New Access</h2>
                        <form onSubmit={handleRegister} className="flex gap-4">
                            <input
                                className="flex-1 bg-slate-900 border border-slate-700 rounded-lg p-3 font-mono uppercase"
                                placeholder="Plate Number (e.g. ABCD12)"
                                value={newPlate.number}
                                onChange={e => setNewPlate({ ...newPlate, number: e.target.value })}
                                required
                            />
                            <input
                                className="flex-1 bg-slate-900 border border-slate-700 rounded-lg p-3"
                                placeholder="Owner Name"
                                value={newPlate.owner}
                                onChange={e => setNewPlate({ ...newPlate, owner: e.target.value })}
                                required
                            />
                            <button className="bg-blue-600 hover:bg-blue-500 px-6 rounded-lg font-bold transition-colors">
                                Submit
                            </button>
                        </form>
                    </div>
                </div>

                {/* Right: Live Feed Preview */}
                <div className="space-y-6">
                    <div className="bg-slate-800 rounded-2xl p-4 border border-slate-700">
                        <h3 className="font-bold text-slate-400 mb-4 text-xs uppercase tracking-wider">Live Gate Feed</h3>
                        <div className="aspect-video bg-black rounded-lg overflow-hidden relative">
                            <img
                                src="http://192.168.196.100:5001/video_feed"
                                className="w-full h-full object-cover"
                                onError={(e) => e.target.style.display = 'none'}
                            />
                        </div>
                    </div>

                    <div className="bg-slate-800 rounded-2xl p-4 border border-slate-700">
                        <h3 className="font-bold text-slate-400 mb-4 text-xs uppercase tracking-wider">Recent Activity</h3>
                        <div className="space-y-3">
                            {detections.map((d, i) => (
                                <div key={i} className="flex items-center justify-between text-sm">
                                    <span className="font-mono font-bold text-slate-300">{d.plate}</span>
                                    <span className={`text-xs ${d.status === 'GRANTED' ? 'text-green-400' : 'text-red-400'}`}>{d.status}</span>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>

            </div>
        </div>
    );
}

export default UserDashboard;
