import { useState, useEffect } from 'react';
import axios from 'axios';
import io from 'socket.io-client';
import { Users, CheckCircle, XCircle, Shield, Trash2, Camera, AlertCircle, Database, X, Image, ChevronLeft, ChevronRight } from 'lucide-react';
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 AdminDashboard({ token }) {
    const { t } = useTranslation();
    const [users, setUsers] = useState([]);
    const [plates, setPlates] = useState([]);
    const [newUser, setNewUser] = useState({ username: '', password: '', role: 'USER' });
    const [activeTab, setActiveTab] = useState('monitor'); // 'monitor' | 'plates' | 'users' | 'visitors'

    // Monitor State
    const [detections, setDetections] = useState([]);
    const [historyLogs, setHistoryLogs] = useState([]);
    const [viewMode, setViewMode] = useState('live'); // 'live' | 'history'
    const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]);

    // Visitor State
    const [activePeople, setActivePeople] = useState([]);
    const [searchRut, setSearchRut] = useState('');
    const [searchResult, setSearchResult] = useState(null); // null | { found: true, data: ... } | { found: false }

    // Dataset State
    const [datasetCount, setDatasetCount] = useState(0);
    const [showDatasetModal, setShowDatasetModal] = useState(false);
    const [datasetImages, setDatasetImages] = useState([]);
    const [selectedImage, setSelectedImage] = useState(null);
    const [datasetPage, setDatasetPage] = useState(1);
    const [datasetTotalPages, setDatasetTotalPages] = useState(1);
    const [datasetTotal, setDatasetTotal] = useState(0);

    useEffect(() => {
        fetchData();
        fetchDatasetCount();

        // Live detection listener
        socket.on('new_detection', (data) => {
            setDetections(prev => [data, ...prev].slice(0, 10));
        });

        // Real-time dataset updates
        socket.on('dataset_updated', (data) => {
            setDatasetCount(data.count);
        });

        // Real-time updates for approvals
        socket.on('new_plate_registered', () => fetchData());
        socket.on('new_person_registered', () => fetchData());
        socket.on('plate_status_updated', () => fetchData());
        socket.on('plate_deleted', () => fetchData());
        socket.on('person_deleted', () => fetchData());

        return () => {
            socket.off('new_detection');
            socket.off('dataset_updated');
            socket.off('new_plate_registered');
            socket.off('new_person_registered');
            socket.off('plate_status_updated');
            socket.off('plate_deleted');
            socket.off('person_deleted');
        };
    }, [token]);

    useEffect(() => {
        if (viewMode === 'history' && activeTab === 'monitor') {
            fetchHistory(selectedDate);
        }
    }, [viewMode, selectedDate, activeTab]);

    const fetchData = async () => {
        try {
            const authHeader = { headers: { Authorization: `Bearer ${token}` } };
            const [usersRes, platesRes, recentRes, peopleRes] = await Promise.all([
                axios.get(`${API_URL}/api/auth`, authHeader).catch(err => ({ data: [] })),
                axios.get(`${API_URL}/api/plates`, authHeader),
                axios.get(`${API_URL}/api/recent`, authHeader),
                axios.get(`${API_URL}/api/people`, authHeader)
            ]);
            setUsers(usersRes.data);
            setPlates(platesRes.data);
            setDetections(recentRes.data.map(log => ({
                plate: log.plateNumber,
                status: log.accessStatus,
                timestamp: log.timestamp
            })));
            setActivePeople(peopleRes.data);
        } catch (err) {
            console.error(err);
        }
    };

    const fetchHistory = async (date) => {
        try {
            const res = await axios.get(`${API_URL}/api/history?date=${date}`);
            setHistoryLogs(res.data);
        } catch (err) {
            console.error(err);
        }
    };

    const fetchDatasetCount = async () => {
        try {
            const res = await axios.get('/dataset/count');
            setDatasetCount(res.data.plates_captured || 0);
        } catch (err) {
            console.log('Dataset count not available');
        }
    };

    const fetchDatasetImages = async (page = 1) => {
        try {
            const res = await axios.get(`/dataset/list?page=${page}&per_page=50`);
            setDatasetImages(res.data.images || []);
            setDatasetPage(res.data.page || 1);
            setDatasetTotalPages(res.data.total_pages || 1);
            setDatasetTotal(res.data.total || 0);
        } catch (err) {
            console.error('Error fetching dataset images');
        }
    };

    const openDatasetModal = () => {
        setDatasetPage(1);
        fetchDatasetImages(1);
        setShowDatasetModal(true);
    };

    const handleDatasetPageChange = (newPage) => {
        if (newPage >= 1 && newPage <= datasetTotalPages) {
            setDatasetPage(newPage);
            fetchDatasetImages(newPage);
        }
    };

    const handleSearchRut = (e) => {
        e.preventDefault();
        const normalizedRut = searchRut.replace(/\./g, '').toUpperCase();
        const found = activePeople.find(p => p.rut.toUpperCase() === normalizedRut);

        if (found) {
            setSearchResult({ found: true, data: found });
        } else {
            setSearchResult({ found: false });
        }
    };

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

    const handleBulkApprove = async (userId) => {
        if (!confirm('Approve ALL pending visitors for this user?')) return;
        try {
            await axios.post(`${API_URL}/api/people/bulk-approve`, { userId }, {
                headers: { Authorization: `Bearer ${token}` }
            });
            fetchData();
            alert('All visitors approved');
        } catch (err) {
            alert(err.message);
        }
    };

    const StatusBadge = ({ status }) => (
        <span className={`px-2 py-1 rounded text-xs font-bold ${status === 'GRANTED' ? 'bg-green-600 text-white' :
            status === 'DENIED' ? 'bg-red-600 text-white' :
                'bg-yellow-600 text-white'
            }`}>
            {status}
        </span>
    );

    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" />
                        {t('title')}
                    </h1>
                    <div className="flex items-center gap-4">
                        <div className="flex bg-slate-800 rounded-lg p-1">
                            <button
                                onClick={() => setActiveTab('monitor')}
                                className={`px-4 py-2 rounded-md transition-all ${activeTab === 'monitor' ? 'bg-purple-600' : 'hover:text-purple-400'}`}
                            >
                                {t('monitor_area')}
                            </button>
                            <button
                                onClick={() => setActiveTab('plates')}
                                className={`px-4 py-2 rounded-md transition-all ${activeTab === 'plates' ? 'bg-purple-600' : 'hover:text-purple-400'}`}
                            >
                                {t('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'}`}
                            >
                                {t('user_management')}
                            </button>
                            <button onClick={() => setActiveTab('visitors')} className={`px-4 py-2 rounded-md transition-all ${activeTab === 'visitors' ? 'bg-purple-600' : 'hover:text-purple-400'}`}>
                                {t('visitor_approvals')}
                            </button>
                        </div>
                        <LanguageSelector />
                    </div>
                </header>

                {activeTab === 'monitor' && (
                    <div className="space-y-6">
                        <div className="flex justify-between items-center">
                            <h2 className="text-xl font-bold flex items-center gap-2">
                                <Camera /> {t('monitor_area')}
                            </h2>
                            <div className="flex items-center gap-4">
                                {/* Dataset Counter - Clickable */}
                                <button
                                    onClick={openDatasetModal}
                                    className="flex items-center gap-2 bg-gradient-to-r from-emerald-900/50 to-teal-900/50 px-4 py-2 rounded-lg border border-emerald-700/50 hover:from-emerald-800/50 hover:to-teal-800/50 transition-all cursor-pointer"
                                >
                                    <Database size={18} className="text-emerald-400" />
                                    <span className="text-emerald-300 font-mono font-bold">{datasetCount}</span>
                                    <span className="text-emerald-400/70 text-sm">capturas</span>
                                </button>
                                <div className="flex bg-slate-800 rounded p-1">
                                    <button onClick={() => setViewMode('live')} className={`px-3 py-1 rounded ${viewMode === 'live' ? 'bg-blue-600' : ''}`}>Live</button>
                                    <button onClick={() => setViewMode('history')} className={`px-3 py-1 rounded ${viewMode === 'history' ? 'bg-blue-600' : ''}`}>History</button>
                                </div>
                            </div>
                        </div>

                        {/* Visitor Lookup Banner */}
                        <div className="bg-slate-800 rounded-xl p-6 border border-slate-700">
                            <h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-slate-300">
                                <Shield size={20} /> {t('visitor_check')}
                            </h3>
                            <form onSubmit={handleSearchRut} className="flex gap-4">
                                <input
                                    className="flex-1 bg-slate-900 border border-slate-600 rounded-lg px-4 py-3 font-mono text-lg tracking-wider uppercase focus:ring-2 focus:ring-blue-500 outline-none transition-all"
                                    placeholder={t('enter_rut')}
                                    value={searchRut}
                                    onChange={e => setSearchRut(e.target.value)}
                                />
                                <button className="bg-blue-600 hover:bg-blue-500 text-white px-8 rounded-lg font-bold transition-all shadow-lg shadow-blue-900/50">
                                    {t('check_status')}
                                </button>
                            </form>

                            {searchResult && (
                                <div className={`mt-6 rounded-xl p-6 border relative animate-in fade-in slide-in-from-top-4 duration-300 ${searchResult.found ? 'bg-gradient-to-r from-blue-900/50 to-cyan-900/50 border-blue-500/50' : 'bg-gradient-to-r from-red-900/50 to-orange-900/50 border-red-500/50'}`}>
                                    <button
                                        onClick={() => { setSearchResult(null); setSearchRut(''); }}
                                        className="absolute top-4 right-4 text-slate-400 hover:text-white transition-colors bg-slate-800/50 rounded-full p-1"
                                    >
                                        <XCircle size={24} />
                                    </button>

                                    {searchResult.found ? (
                                        <div className="flex items-start gap-4">
                                            <div className="bg-green-500/20 p-3 rounded-full text-green-400">
                                                <CheckCircle size={32} />
                                            </div>
                                            <div>
                                                <h4 className="text-xl font-bold text-white mb-1">{t('visitor_found')}</h4>
                                                <div className="space-y-1 text-slate-300">
                                                    <p className="flex items-center gap-2"><Users size={16} className="text-blue-400" /> Visitor: <span className="font-semibold text-white">{searchResult.data.name}</span></p>
                                                    <p className="flex items-center gap-2"><Shield size={16} className="text-purple-400" /> Status: <span className="font-bold text-green-400">{searchResult.data.status}</span></p>
                                                    <p className="text-sm text-slate-500 mt-2 border-t border-slate-700/50 pt-2">
                                                        {t('registered_by')}: <span className="text-slate-300 font-mono">@{searchResult.data.addedBy?.username || 'Unknown'}</span>
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                    ) : (
                                        <div className="flex items-center gap-4">
                                            <div className="bg-red-500/20 p-3 rounded-full text-red-400">
                                                <AlertCircle size={32} />
                                            </div>
                                            <div>
                                                <h4 className="text-xl font-bold text-white mb-1">{t('visitor_not_found')}</h4>
                                                <p className="text-slate-300">{t('no_record')}</p>
                                            </div>
                                        </div>
                                    )}
                                </div>
                            )}
                        </div>

                        {viewMode === 'live' ? (
                            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                                <div className="bg-black rounded-xl overflow-hidden aspect-video border border-slate-700 relative">
                                    <img
                                        src="/video_feed"
                                        className="w-full h-full object-cover"
                                        onError={(e) => e.target.style.display = 'none'}
                                    />
                                    <div className="absolute top-4 left-4 bg-red-600 px-2 py-1 rounded text-xs font-bold animate-pulse">LIVE</div>
                                </div>
                                <div className="bg-slate-800 rounded-xl p-4 border border-slate-700 h-[400px] overflow-y-auto">
                                    <h3 className="font-bold mb-4 text-slate-400">Recent Detections</h3>
                                    <div className="space-y-2">
                                        {detections.map((d, i) => (
                                            <div key={i} className="flex justify-between items-center p-3 bg-slate-900 rounded border border-slate-700">
                                                <span className="font-mono text-lg font-bold">{d.plate}</span>
                                                <div className="flex items-center gap-2">
                                                    <span className="text-xs text-slate-500">{new Date(d.timestamp).toLocaleTimeString()}</span>
                                                    <StatusBadge status={d.status} />
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            </div>
                        ) : (
                            <div className="bg-slate-800 rounded-xl p-6 border border-slate-700">
                                <div className="flex gap-4 mb-6">
                                    <input
                                        type="date"
                                        value={selectedDate}
                                        onChange={(e) => setSelectedDate(e.target.value)}
                                        className="bg-slate-900 border border-slate-600 rounded px-4 py-2"
                                    />
                                </div>
                                <div className="space-y-2">
                                    {historyLogs.map(log => (
                                        <div key={log.id} className="flex justify-between items-center p-3 bg-slate-900 rounded border border-slate-700">
                                            <div className="flex items-center gap-4">
                                                <span className="font-mono text-lg font-bold">{log.plateNumber}</span>
                                                <span className="text-slate-500">{new Date(log.timestamp).toLocaleString()}</span>
                                            </div>
                                            <StatusBadge status={log.accessStatus} />
                                        </div>
                                    ))}
                                    {historyLogs.length === 0 && <p className="text-slate-500 text-center py-8">No logs found for this date.</p>}
                                </div>
                            </div>
                        )}
                    </div>
                )}

                {activeTab === 'plates' && (
                    <div className="bg-slate-800 rounded-2xl p-6 border border-slate-700">
                        <h2 className="text-xl font-semibold mb-6">{t('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} /> {t('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} /> {t('deny')}
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>

                        <h2 className="text-xl font-semibold mt-10 mb-6">{t('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 className="text-xs text-slate-600 mt-1">Added by: {plate.addedBy?.username || 'System'}</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'}`}>
                                            {t(plate.status.toLowerCase()) || 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">{t('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={t('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={t('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">{t('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">{t('user_list')}</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>
                )}

                {activeTab === 'visitors' && (
                    <div className="bg-slate-800 rounded-2xl p-6 border border-slate-700">
                        <h2 className="text-xl font-bold mb-6">{t('visitor_approvals')}</h2>

                        {Object.values(activePeople.filter(p => p.status === 'PENDING').reduce((acc, p) => {
                            const uId = p.addedById || 0;
                            if (!acc[uId]) acc[uId] = { user: p.addedBy?.username || 'Unknown', userId: uId, items: [] };
                            acc[uId].items.push(p);
                            return acc;
                        }, {})).map(group => (
                            <div key={group.userId} className="mb-6 bg-slate-900 p-4 rounded-xl border border-slate-700">
                                <div className="flex justify-between items-center mb-4 border-b border-slate-700 pb-2">
                                    <h3 className="font-bold text-lg text-purple-400">User: {group.user}</h3>
                                    <button onClick={() => handleBulkApprove(group.userId)} className="bg-green-600 hover:bg-green-500 px-4 py-1 rounded text-sm font-bold">
                                        Approve All ({group.items.length})
                                    </button>
                                </div>
                                <div className="space-y-2">
                                    {group.items.map(p => (
                                        <div key={p.id} className="flex justify-between text-sm text-slate-300">
                                            <span>{p.name} ({p.rut})</span>
                                            <span>{parseInt((new Date(p.endDate) - new Date(p.startDate)) / (1000 * 60 * 60 * 24))} Days</span>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        ))}

                        {activePeople.filter(p => p.status === 'PENDING').length === 0 && <p className="text-slate-500">No pending visitors.</p>}
                    </div>
                )}
            </div>

            {/* Dataset Gallery Modal */}
            {showDatasetModal && (
                <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4">
                    <div className="bg-slate-900 rounded-2xl border border-slate-700 w-full max-w-6xl max-h-[90vh] overflow-hidden flex flex-col">
                        {/* Header */}
                        <div className="flex items-center justify-between p-4 border-b border-slate-700">
                            <div className="flex items-center gap-3">
                                <Database className="text-emerald-400" size={24} />
                                <h2 className="text-xl font-bold text-white">Dataset de Capturas</h2>
                                <span className="bg-emerald-600 px-2 py-1 rounded text-sm font-mono">{datasetTotal} imágenes</span>
                            </div>
                            <button
                                onClick={() => { setShowDatasetModal(false); setSelectedImage(null); }}
                                className="text-slate-400 hover:text-white p-2 hover:bg-slate-800 rounded-lg transition-colors"
                            >
                                <X size={24} />
                            </button>
                        </div>

                        {/* Content */}
                        <div className="flex-1 overflow-auto p-4">
                            {selectedImage ? (
                                /* Image Preview */
                                <div className="flex flex-col items-center gap-4">
                                    <button
                                        onClick={() => setSelectedImage(null)}
                                        className="self-start flex items-center gap-2 text-slate-400 hover:text-white transition-colors"
                                    >
                                        ← Volver a galería
                                    </button>
                                    <img
                                        src={selectedImage.url}
                                        alt={selectedImage.plate}
                                        className="max-w-full max-h-[60vh] rounded-lg border border-slate-700"
                                    />
                                    <div className="bg-slate-800 px-4 py-2 rounded-lg">
                                        <span className="text-slate-400">Patente: </span>
                                        <span className="font-mono font-bold text-emerald-400 text-lg">{selectedImage.plate}</span>
                                    </div>
                                </div>
                            ) : (
                                /* Image Grid */
                                <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                                    {datasetImages.map((img, idx) => (
                                        <div
                                            key={idx}
                                            onClick={() => setSelectedImage(img)}
                                            className="cursor-pointer group relative aspect-video bg-slate-800 rounded-lg overflow-hidden border border-slate-700 hover:border-emerald-500 transition-all"
                                        >
                                            <img
                                                src={img.url}
                                                alt={img.plate}
                                                className="w-full h-full object-cover group-hover:scale-105 transition-transform"
                                                loading="lazy"
                                            />
                                            <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-2">
                                                <span className="font-mono text-sm text-emerald-300 font-bold">{img.plate}</span>
                                            </div>
                                        </div>
                                    ))}
                                    {datasetImages.length === 0 && (
                                        <div className="col-span-full text-center py-12 text-slate-500">
                                            <Image size={48} className="mx-auto mb-4 opacity-50" />
                                            <p>No hay capturas en el dataset</p>
                                        </div>
                                    )}
                                </div>
                            )}
                        </div>

                        {/* Pagination Footer */}
                        {!selectedImage && datasetTotalPages > 1 && (
                            <div className="flex items-center justify-center gap-4 p-4 border-t border-slate-700 bg-slate-800/50">
                                <button
                                    onClick={() => handleDatasetPageChange(datasetPage - 1)}
                                    disabled={datasetPage === 1}
                                    className="flex items-center gap-1 px-3 py-2 rounded-lg bg-slate-700 hover:bg-slate-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                                >
                                    <ChevronLeft size={18} />
                                    Anterior
                                </button>
                                <div className="flex items-center gap-2 text-slate-300">
                                    <span>Página</span>
                                    <span className="bg-emerald-600 px-3 py-1 rounded font-mono font-bold">{datasetPage}</span>
                                    <span>de</span>
                                    <span className="font-mono font-bold">{datasetTotalPages}</span>
                                </div>
                                <button
                                    onClick={() => handleDatasetPageChange(datasetPage + 1)}
                                    disabled={datasetPage === datasetTotalPages}
                                    className="flex items-center gap-1 px-3 py-2 rounded-lg bg-slate-700 hover:bg-slate-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                                >
                                    Siguiente
                                    <ChevronRight size={18} />
                                </button>
                            </div>
                        )}
                    </div>
                </div>
            )}
        </div>
    );
}

export default AdminDashboard;
