import { useState, useEffect } from 'react';
import axios from 'axios';
import { Car, Clock, CheckCircle, AlertCircle, Users, Trash2, PlusCircle, UserPlus, AlertTriangle } from 'lucide-react';
import io from 'socket.io-client';
import { useTranslation } from 'react-i18next';
import LanguageSelector from '../components/LanguageSelector';

const API_URL = import.meta.env.VITE_API_URL || '';
const socket = io(API_URL);

function UserDashboard({ token, username }) {
    const { t } = useTranslation();
    const [plates, setPlates] = useState([]);
    const [newPlate, setNewPlate] = useState({ number: '', owner: '' });
    const [detections, setDetections] = useState([]);
    const [people, setPeople] = useState([]);
    const [newPerson, setNewPerson] = useState({ name: '', rut: '', durationDays: 1 });

    useEffect(() => {
        fetchPlates();
        fetchPeople();

        // 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));
        });

        // Real-time status updates
        socket.on('new_plate_registered', () => fetchPlates()); // Sync when plate added
        socket.on('plate_status_updated', () => fetchPlates());
        socket.on('people_updated', () => fetchPeople());

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

    const fetchPlates = async () => {
        try {
            const res = await axios.get(`${API_URL}/api/plates`, {
                headers: { Authorization: `Bearer ${token}` }
            });
            // Backend already filters by user, so use data directly
            setPlates(res.data);
        } catch (err) {
            console.error(err);
        }
    };

    const fetchPeople = async () => {
        try {
            const res = await axios.get(`${API_URL}/api/people`, {
                headers: { Authorization: `Bearer ${token}` }
            });
            setPeople(res.data);
        } 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 removed for better UX
        } catch (err) {
            alert('Error: ' + err.message);
        }
    };

    const handleAddPerson = async (e) => {
        e.preventDefault();
        try {
            await axios.post(`${API_URL}/api/people`, newPerson, {
                headers: { Authorization: `Bearer ${token}` }
            });
            setNewPerson({ name: '', rut: '', durationDays: 1 });
            fetchPeople();
            // Alert removed for better UX
        } catch (err) {
            alert('Error: ' + (err.response?.data?.error || err.message));
        }
    };

    const handleDeletePlate = async (id) => {
        if (!confirm(t('confirm_delete_plate'))) return;
        try {
            await axios.delete(`${API_URL}/api/plates/${id}`, {
                headers: { Authorization: `Bearer ${token}` }
            });
            fetchPlates();
        } catch (err) {
            alert(err.response?.data?.error || err.message);
        }
    };

    const handleDeletePerson = async (id) => {
        if (!confirm(t('confirm_delete_visitor'))) return;
        try {
            await axios.delete(`${API_URL}/api/people/${id}`, {
                headers: { Authorization: `Bearer ${token}` }
            });
            fetchPeople();
        } catch (err) {
            alert(err.response?.data?.error || err.message);
        }
    };

    return (
        <div className="min-h-screen bg-slate-900 text-slate-100 p-8">
            <div className="max-w-6xl mx-auto space-y-8">

                <header className="flex justify-between items-center">
                    <div>
                        <h1 className="text-3xl font-bold bg-gradient-to-r from-blue-400 to-cyan-300 bg-clip-text text-transparent mb-2">
                            {t('welcome')}, {username}
                        </h1>
                        <p className="text-slate-400">Manage your vehicles and visitors.</p>
                    </div>
                    <LanguageSelector />
                </header>

                <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                    {/* Plate Registration Form (Existing) */}
                    <div className="bg-slate-800 rounded-2xl p-6 border border-slate-700">
                        <h2 className="text-xl font-bold mb-4 flex items-center gap-2">
                            <PlusCircle className="text-blue-500" /> {t('register_plate')}
                        </h2>
                        <form onSubmit={handleRegister} className="space-y-4">
                            <input
                                className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 font-mono text-lg"
                                placeholder={t('plate_number')}
                                value={newPlate.number}
                                onChange={e => setNewPlate({ ...newPlate, number: e.target.value.toUpperCase() })}
                                required
                            />
                            <input
                                className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3"
                                placeholder={t('owner_desc')}
                                value={newPlate.owner}
                                onChange={e => setNewPlate({ ...newPlate, owner: e.target.value })}
                                required
                            />
                            <button className="w-full py-3 bg-blue-600 hover:bg-blue-500 rounded-lg font-bold">{t('submit_plate')}</button>
                        </form>
                    </div>

                    {/* Visitor Registration Form (Existing) */}
                    <div className="bg-slate-800 rounded-2xl p-6 border border-slate-700">
                        <h2 className="text-xl font-bold mb-4 flex items-center gap-2">
                            <UserPlus className="text-purple-500" /> {t('register_visitor')}
                        </h2>
                        <form onSubmit={handleAddPerson} className="space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                                <input
                                    className="bg-slate-900 border border-slate-700 rounded-lg p-3"
                                    placeholder={t('visitor_rut')}
                                    value={newPerson.rut}
                                    onChange={e => setNewPerson({ ...newPerson, rut: e.target.value })}
                                    required
                                />
                                <select
                                    className="bg-slate-900 border border-slate-700 rounded-lg p-3"
                                    value={newPerson.durationDays}
                                    onChange={e => setNewPerson({ ...newPerson, durationDays: parseInt(e.target.value) })}
                                    required
                                >
                                    <option value="1">{t('1_day')}</option>
                                    <option value="2">{t('2_days')}</option>
                                    <option value="7">{t('1_week')}</option>
                                </select>
                            </div>
                            <input
                                className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3"
                                placeholder={t('full_name')}
                                value={newPerson.name}
                                onChange={e => setNewPerson({ ...newPerson, name: e.target.value })}
                                required
                            />
                            <button className="w-full py-3 bg-purple-600 hover:bg-purple-500 rounded-lg font-bold">{t('submit_visitor')}</button>
                        </form>
                    </div>
                </div>

                {/* My Plates List */}
                <div>
                    <h2 className="text-2xl font-bold mb-4">{t('my_plates_title')}</h2>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        {plates.length === 0 && <p className="text-slate-500 col-span-3">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 group">
                                <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 className="flex items-center gap-3">
                                    {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} /> {t('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} /> {t('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">
                                            <AlertTriangle size={14} /> {t('denied')}
                                        </span>
                                    )}
                                    <button
                                        onClick={() => handleDeletePlate(plate.id)}
                                        className="text-slate-600 hover:text-red-500 transition-colors p-1"
                                        title={t('delete')}
                                    >
                                        <Trash2 size={18} />
                                    </button>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>

                {/* My Visitors List */}
                <div>
                    <h2 className="text-2xl font-bold mb-4">{t('my_visitors_title')}</h2>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        {people.length === 0 && <p className="text-slate-500 col-span-3">No visitors registered.</p>}
                        {people.map(p => (
                            <div key={p.id} className="flex items-center justify-between p-4 bg-slate-900 rounded-xl border border-slate-700">
                                <div>
                                    <div className="font-bold">{p.name}</div>
                                    <div className="text-sm text-slate-400 font-mono">{p.rut}</div>
                                    <div className="text-xs text-slate-500 mt-1">Until: {new Date(p.endDate).toLocaleDateString()}</div>
                                </div>
                                <div className="flex items-center gap-3">
                                    <span className={`px-2 py-1 rounded text-xs font-bold ${p.status === 'APPROVED' ? 'bg-green-900 text-green-300' :
                                        p.status === 'DENIED' ? 'bg-red-900 text-red-300' : 'bg-yellow-900 text-yellow-300'
                                        }`}>
                                        {p.status === 'APPROVED' ? t('approved') : p.status === 'DENIED' ? t('denied') : t('pending')}
                                    </span>
                                    <button
                                        onClick={() => handleDeletePerson(p.id)}
                                        className="text-slate-600 hover:text-red-500 transition-colors p-1"
                                        title={t('delete')}
                                    >
                                        <Trash2 size={18} />
                                    </button>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>

            </div>
        </div>
    );
}

export default UserDashboard;
