import { Link } from '@inertiajs/react';
import { useState, useEffect } from 'react';
import ConfirmBooking from './bookings/ConfirmBooking';
import { formatDate } from '@/utils/dateFormatter';

const themeColor = '#c9a227';

export default function Dashboard({ stats, bookingTrends = [], recentBookings = [], roomCategories = [], bookingsByCategory = [], revenueByCategory = [], statusDistribution = [] }) {
    const [currentDateTime, setCurrentDateTime] = useState(new Date());
    const [selectedBooking, setSelectedBooking] = useState(null);
    const [isBookingModalOpen, setIsBookingModalOpen] = useState(false);
    const [currentLang, setCurrentLang] = useState('en');

    const translations = {
        en: {
            dashboardOverview: 'Dashboard Overview',
            welcomeMessage: "Welcome back! Here's what's happening at Matergo Hotel",
            currentDateTime: 'Current Date & Time',
            viewAllBookings: 'View All Bookings',
            viewDetails: 'View Details',
            totalRoomCategories: 'Total Room Categories',
            availableRoomsToday: 'Available Rooms (Today)',
            confirmedBookingsToday: 'Confirmed Bookings (Today)',
            pendingBookings: 'Pending Bookings',
            monthlyRevenueUsd: 'Monthly Revenue (USD/BIF)',
            occupancyRate: 'Occupancy Rate',
            monthlyBookings: 'Monthly Bookings',
            unreadMessages: 'Unread Messages',
            bookingTrends: 'Booking Trends (Last 6 Months)',
            confirmed: 'Confirmed',
            pending: 'Pending',
            roomCategories: 'Room Categories',
            rooms: 'rooms',
            noRoomCategories: 'No room categories available',
            totalRevenueAllTime: 'Total Revenue (All Time)',
            vsLastMonth: 'vs last month',
            currentlyBookedRooms: 'Currently Booked Rooms',
            occupied: 'Occupied',
            quickStats: 'Quick Stats',
            eventRooms: 'Event Rooms',
            services: 'Services',
            totalBookings: 'Total Bookings',
            cancelled: 'Cancelled',
            bookingsByCategory: 'Bookings by Category',
            bookingStatus: 'Booking Status',
            revenueByCategory: 'Revenue by Category',
            noBookingData: 'No booking data available',
            noStatusData: 'No status data available',
            noRevenueData: 'No revenue data available',
            recentBookings: 'Recent Bookings',
            viewAll: 'View All',
            reference: 'Reference',
            guestName: 'Guest Name',
            room: 'Room',
            checkIn: 'Check-in',
            checkOut: 'Check-out',
            amount: 'Amount',
            status: 'Status',
            noRecentBookings: 'No recent bookings',
            revenueLabel: 'Revenue',
            revenueAxisLabel: 'Revenue ($)',
            statuses: {
                confirmed: 'Confirmed',
                pending: 'Pending',
                cancelled: 'Cancelled',
            },
        },
        fr: {
            dashboardOverview: "Aperçu du tableau de bord",
            welcomeMessage: "Bon retour ! Voici ce qui se passe à l'hôtel Matergo",
            currentDateTime: "Date et heure actuelles",
            viewAllBookings: "Voir toutes les réservations",
            viewDetails: "Voir les détails",
            totalRoomCategories: "Nombre total de catégories de chambres",
            availableRoomsToday: "Chambres disponibles (aujourd'hui)",
            confirmedBookingsToday: "Réservations confirmées (aujourd'hui)",
            pendingBookings: "Réservations en attente",
            monthlyRevenueUsd: "Revenus mensuels (USD/BIF)",
            occupancyRate: "Taux d'occupation",
            monthlyBookings: "Réservations mensuelles",
            unreadMessages: "Messages non lus",
            bookingTrends: "Tendances des réservations (6 derniers mois)",
            confirmed: "Confirmé",
            pending: "En attente",
            roomCategories: "Catégories de chambres",
            rooms: "chambres",
            noRoomCategories: "Aucune catégorie de chambre disponible",
            totalRevenueAllTime: "Revenus totaux (toutes périodes)",
            vsLastMonth: "par rapport au mois dernier",
            currentlyBookedRooms: "Chambres actuellement réservées",
            occupied: "Occupé",
            quickStats: "Statistiques rapides",
            eventRooms: "Salles d'événements",
            services: "Services",
            totalBookings: "Réservations totales",
            cancelled: "Annulées",
            bookingsByCategory: "Réservations par catégorie",
            bookingStatus: "Statut des réservations",
            revenueByCategory: "Revenus par catégorie",
            noBookingData: "Aucune donnée de réservation disponible",
            noStatusData: "Aucune donnée de statut disponible",
            noRevenueData: "Aucune donnée de revenus disponible",
            recentBookings: "Réservations récentes",
            viewAll: "Voir tout",
            reference: "Référence",
            guestName: "Nom du client",
            room: "Chambre",
            checkIn: "Arrivée",
            checkOut: "Départ",
            amount: "Montant",
            status: "Statut",
            noRecentBookings: "Aucune réservation récente",
            revenueLabel: "Revenus",
            revenueAxisLabel: "Revenus ($)",
            statuses: {
                confirmed: "Confirmé",
                pending: "En attente",
                cancelled: "Annulé",
            },
        },
    };
    const t = translations[currentLang] || translations.en;

    useEffect(() => {
        // Update date/time every second
        const interval = setInterval(() => {
            setCurrentDateTime(new Date());
        }, 1000);

        return () => clearInterval(interval);
    }, []);

    useEffect(() => {
        const savedLang = localStorage.getItem('adminLanguage') || 'en';
        setCurrentLang(savedLang);

        const handleLanguageChange = (e) => {
            const newLang = e.detail?.language || localStorage.getItem('adminLanguage') || 'en';
            setCurrentLang(newLang);
        };

        window.addEventListener('adminLanguageChanged', handleLanguageChange);
        window.addEventListener('storage', handleLanguageChange);

        return () => {
            window.removeEventListener('adminLanguageChanged', handleLanguageChange);
            window.removeEventListener('storage', handleLanguageChange);
        };
    }, []);

    // Initialize charts
    useEffect(() => {
        if (typeof window !== 'undefined' && window.Chart) {
            const charts = [];

            // Bookings by Category Pie Chart
            const categoryCtx = document.getElementById('bookingsByCategoryChart');
            if (categoryCtx && bookingsByCategory.length > 0) {
                const categoryChart = new window.Chart(categoryCtx, {
                    type: 'pie',
                    data: {
                        labels: bookingsByCategory.map(item => item.category),
                        datasets: [{
                            data: bookingsByCategory.map(item => item.count),
                            backgroundColor: [
                                '#c9a227',
                                '#28a745',
                                '#17a2b8',
                                '#ffc107',
                                '#dc3545',
                                '#6f42c1',
                                '#e83e8c',
                                '#fd7e14',
                            ],
                            borderWidth: 2,
                            borderColor: '#fff'
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        legend: {
                            position: 'bottom',
                        },
                        tooltips: {
                            callbacks: {
                                label: function(tooltipItem, data) {
                                    const label = data.labels[tooltipItem.index] || '';
                                    const value = data.datasets[0].data[tooltipItem.index] || 0;
                                    const total = data.datasets[0].data.reduce((a, b) => a + b, 0);
                                    const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : 0;
                                    return `${label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    }
                });
                charts.push(categoryChart);
            }

            // Booking Status Distribution Doughnut Chart
            const statusCtx = document.getElementById('statusDistributionChart');
            if (statusCtx && statusDistribution.length > 0) {
                const statusChart = new window.Chart(statusCtx, {
                    type: 'doughnut',
                    data: {
                        labels: statusDistribution.map(item => translateStatus(item.status)),
                        datasets: [{
                            data: statusDistribution.map(item => item.count),
                            backgroundColor: statusDistribution.map(item => item.color),
                            borderWidth: 2,
                            borderColor: '#fff'
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        legend: {
                            position: 'bottom',
                        },
                        tooltips: {
                            callbacks: {
                                label: function(tooltipItem, data) {
                                    const label = data.labels[tooltipItem.index] || '';
                                    const value = data.datasets[0].data[tooltipItem.index] || 0;
                                    const total = data.datasets[0].data.reduce((a, b) => a + b, 0);
                                    const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : 0;
                                    return `${label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    }
                });
                charts.push(statusChart);
            }

            // Revenue by Category Bar Chart
            const revenueCtx = document.getElementById('revenueByCategoryChart');
            if (revenueCtx && revenueByCategory.length > 0) {
                const revenueChart = new window.Chart(revenueCtx, {
                    type: 'bar',
                    data: {
                        labels: revenueByCategory.map(item => item.category),
                        datasets: [{
                            label: t.revenueAxisLabel,
                            data: revenueByCategory.map(item => item.revenue_usd),
                            backgroundColor: themeColor,
                            borderColor: themeColor,
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        legend: {
                            display: false
                        },
                        tooltips: {
                            callbacks: {
                                label: function(tooltipItem, data) {
                                    const usd = tooltipItem.yLabel || 0;
                                    const bif = revenueByCategory[tooltipItem.index]?.revenue_bif || 0;
                                    return `${t.revenueLabel}: $${usd.toLocaleString()} | ${bif.toLocaleString()} BIF`;
                                }
                            }
                        },
                        scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero: true,
                                    callback: function(value) {
                                        return '$' + value.toLocaleString();
                                    }
                                }
                            }]
                        }
                    }
                });
                charts.push(revenueChart);
            }

            return () => {
                // Cleanup charts on unmount
                charts.forEach(chart => {
                    if (chart && typeof chart.destroy === 'function') {
                        chart.destroy();
                    }
                });
            };
        }
    }, [bookingsByCategory, revenueByCategory, statusDistribution, currentLang]);

    const formatDateTime = (date) => {
        const options = { 
            weekday: 'long', 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: currentLang !== 'fr'
        };
        return date.toLocaleDateString(currentLang === 'fr' ? 'fr-FR' : 'en-US', options);
    };

    const translateStatus = (value) => {
        if (!value) {
            return value;
        }
        const key = value.toString().toLowerCase();
        return t.statuses[key] || value;
    };

    const handleBookingClick = (booking) => {
        fetch(`/admin/view_booking/${booking.id}`)
            .then((response) => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then((bookingData) => {
                setSelectedBooking(bookingData);
                setIsBookingModalOpen(true);
            })
            .catch((error) => {
                console.error('Error fetching booking details:', error);
            });
    };
    const {
        totalRoomCategories = 0,
        totalRooms = 0,
        availableRooms = 0,
        totalEventRooms = 0,
        totalServices = 0,
        unreadMessages = 0,
        totalBookings = 0,
        confirmedBookings = 0,
        todayConfirmedBookings = 0,
        pendingBookings = 0,
        cancelledBookings = 0,
        monthlyBookings = 0,
        monthlyConfirmed = 0,
        totalRevenueUsd = 0,
        totalRevenueBif = 0,
        monthlyRevenueUsd = 0,
        monthlyRevenueBif = 0,
        revenueGrowth = 0,
        bookedRooms = 0,
        occupancyRate = 0,
    } = stats || {};

    const maxBookingValue = Math.max(
        ...bookingTrends.map(t => Math.max(t.confirmed || 0, t.pending || 0)),
        1
    );

    const StatCard = ({ title, value, icon, color, link }) => (
        <div className="col-md-6 col-lg-3 mb-4">
            <div className="card shadow-sm border-0 h-100" style={{ borderLeft: `4px solid ${color}` }}>
                <div className="card-body">
                    <div className="d-flex justify-content-between align-items-center">
                        <div>
                            <small className="text-muted d-block mb-1">{title}</small>
                            <h3 className="mb-0 font-weight-bold" style={{ color: color }}>{value}</h3>
                        </div>
                        <div style={{ fontSize: '2.5rem', opacity: 0.2, color: color }}>
                            <i className={icon}></i>
                        </div>
                    </div>
                    {link && (
                        <Link href={link} className="btn btn-sm mt-2" style={{ backgroundColor: color, color: '#fff', borderColor: color }}>
                            {t.viewDetails}
                        </Link>
                    )}
                </div>
            </div>
        </div>
    );

    return (
        <div className="container-fluid">
            <div className="row">
                <div className="col-12">
                    <div className="d-flex justify-content-between align-items-center mb-4">
                        <div>
                            <h2 className="h4 page-title mb-1">{t.dashboardOverview}</h2>
                            <p className="text-muted mb-0">{t.welcomeMessage}</p>
                            <p className="text-muted mb-0 mt-2" style={{ fontSize: '0.9rem' }}>
                                <i className="fe fe-clock mr-1"></i>
                                <strong>{t.currentDateTime}:</strong> {formatDateTime(currentDateTime)}
                            </p>
                        </div>
                        <div>
                            <Link href="/admin/bookings" className="btn btn-primary">
                                <i className="fe fe-calendar mr-2"></i>
                                {t.viewAllBookings}
                            </Link>
                        </div>
                    </div>

                    {/* Main Statistics Cards */}
                    <div className="row mb-4">
                        <StatCard 
                            title={t.totalRoomCategories} 
                            value={totalRoomCategories} 
                            icon="fe fe-home"
                            color={themeColor}
                            link="/admin/accommodations"
                        />
                        <StatCard 
                            title={t.availableRoomsToday} 
                            value={`${availableRooms}/${totalRooms}`} 
                            icon="fe fe-layers"
                            color="#28a745"
                        />
                        <StatCard 
                            title={t.confirmedBookingsToday} 
                            value={todayConfirmedBookings} 
                            icon="fe fe-check-circle"
                            color="#28a745"
                            link="/admin/bookings"
                        />
                        <StatCard 
                            title={t.pendingBookings} 
                            value={pendingBookings} 
                            icon="fe fe-clock"
                            color="#ffc107"
                            link="/admin/bookings"
                        />
                    </div>

                    {/* Secondary Statistics Row */}
                    <div className="row mb-4">
                        <StatCard 
                            title={t.monthlyRevenueUsd} 
                            value={`$${monthlyRevenueUsd.toLocaleString()} | ${monthlyRevenueBif.toLocaleString()} BIF`} 
                            icon="fe fe-dollar-sign"
                            color={themeColor}
                        />
                        <StatCard 
                            title={t.occupancyRate} 
                            value={`${occupancyRate}%`} 
                            icon="fe fe-trending-up"
                            color={occupancyRate >= 70 ? '#28a745' : occupancyRate >= 50 ? '#ffc107' : '#dc3545'}
                        />
                        <StatCard 
                            title={t.monthlyBookings} 
                            value={monthlyBookings} 
                            icon="fe fe-calendar"
                            color={themeColor}
                        />
                        <StatCard 
                            title={t.unreadMessages} 
                            value={unreadMessages} 
                            icon="fe fe-mail"
                            color={unreadMessages > 0 ? '#dc3545' : '#6c757d'}
                            link="/admin/messages"
                        />
                    </div>

                    {/* Charts and Data Visualization Row */}
                    <div className="row mb-4">
                        {/* Booking Trends Chart */}
                        <div className="col-lg-8 mb-4">
                            <div className="card shadow-sm border-0">
                                <div className="card-header bg-white border-bottom">
                                    <h5 className="mb-0 font-weight-bold">
                                        <i className="fe fe-trending-up mr-2" style={{ color: themeColor }}></i>
                                        {t.bookingTrends}
                                    </h5>
                                </div>
                                <div className="card-body">
                                    <div className="booking-chart-container">
                                        <div className="d-flex justify-content-center mb-3">
                                            <div className="mr-4">
                                                <span className="d-inline-block mr-2" style={{ width: '12px', height: '12px', backgroundColor: '#28a745', borderRadius: '2px' }}></span>
                                                <small className="text-muted">{t.confirmed}</small>
                                            </div>
                                            <div>
                                                <span className="d-inline-block mr-2" style={{ width: '12px', height: '12px', backgroundColor: '#ffc107', borderRadius: '2px' }}></span>
                                                <small className="text-muted">{t.pending}</small>
                                            </div>
                                        </div>
                                        <div style={{ height: '250px', position: 'relative' }}>
                                            <div className="d-flex align-items-end justify-content-between h-100" style={{ padding: '10px 0' }}>
                                                {bookingTrends.map((trend, index) => {
                                                    const confirmedHeight = maxBookingValue > 0 
                                                        ? ((trend.confirmed || 0) / maxBookingValue) * 100 
                                                        : 0;
                                                    const pendingHeight = maxBookingValue > 0 
                                                        ? ((trend.pending || 0) / maxBookingValue) * 100 
                                                        : 0;
                                                    
                                                    return (
                                                        <div key={index} className="flex-fill d-flex flex-column align-items-center mx-1">
                                                            <div className="d-flex align-items-end mb-2" style={{ height: '200px', width: '100%', position: 'relative' }}>
                                                                <div 
                                                                    className="mb-1" 
                                                                    style={{
                                                                        width: '45%',
                                                                        backgroundColor: '#28a745',
                                                                        height: `${confirmedHeight}%`,
                                                                        borderRadius: '4px 4px 0 0',
                                                                        transition: 'height 0.3s ease'
                                                                    }}
                                                                    title={`${t.confirmed}: ${trend.confirmed}`}
                                                                ></div>
                                                                <div 
                                                                    className="mb-1 ml-1" 
                                                                    style={{
                                                                        width: '45%',
                                                                        backgroundColor: '#ffc107',
                                                                        height: `${pendingHeight}%`,
                                                                        borderRadius: '4px 4px 0 0',
                                                                        transition: 'height 0.3s ease'
                                                                    }}
                                                                    title={`${t.pending}: ${trend.pending}`}
                                                                ></div>
                                                            </div>
                                                            <small className="text-muted text-center" style={{ fontSize: '0.75rem' }}>
                                                                {trend.month}
                                                            </small>
                                                        </div>
                                                    );
                                                })}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Room Categories Distribution */}
                        <div className="col-lg-4 mb-4">
                            <div className="card shadow-sm border-0 h-100">
                                <div className="card-header bg-white border-bottom">
                                    <h5 className="mb-0 font-weight-bold">
                                        <i className="fe fe-grid mr-2" style={{ color: themeColor }}></i>
                                        {t.roomCategories}
                                    </h5>
                                </div>
                                <div className="card-body">
                                    {roomCategories && roomCategories.length > 0 ? (
                                        <div className="room-categories-list">
                                            {roomCategories.map((category, index) => {
                                                const maxRooms = Math.max(...roomCategories.map(c => c.available_rooms || 0), 1);
                                                const widthPercent = ((category.available_rooms || 0) / maxRooms) * 100;
                                                
                                                return (
                                                    <div key={index} className="mb-3">
                                                        <div className="d-flex justify-content-between mb-1">
                                                            <small className="font-weight-medium">{category.category}</small>
                                                            <small className="text-muted">{category.available_rooms || 0} {t.rooms}</small>
                                                        </div>
                                                        <div className="progress" style={{ height: '8px', borderRadius: '4px' }}>
                                                            <div 
                                                                className="progress-bar" 
                                                                role="progressbar" 
                                                                style={{ 
                                                                    width: `${widthPercent}%`, 
                                                                    backgroundColor: themeColor,
                                                                    transition: 'width 0.3s ease'
                                                                }}
                                                            ></div>
                                                        </div>
                                                    </div>
                                                );
                                            })}
                                        </div>
                                    ) : (
                                        <p className="text-muted text-center mb-0">{t.noRoomCategories}</p>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Revenue and Additional Stats */}
                    <div className="row mb-4">
                        <div className="col-lg-4 mb-4">
                            <div className="card shadow-sm border-0">
                                <div className="card-body text-center">
                                    <i className="fe fe-dollar-sign mb-3" style={{ fontSize: '3rem', color: themeColor, opacity: 0.3 }}></i>
                                    <h3 className="font-weight-bold mb-1" style={{ color: themeColor }}>
                                        ${totalRevenueUsd.toLocaleString()} | ${totalRevenueBif.toLocaleString()} BIF
                                    </h3>
                                    <p className="text-muted mb-2">{t.totalRevenueAllTime}</p>
                                    <div className={`badge ${revenueGrowth >= 0 ? 'badge-success' : 'badge-danger'}`}>
                                        {revenueGrowth >= 0 ? '+' : ''}{revenueGrowth}% {t.vsLastMonth}
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="col-lg-4 mb-4">
                            <div className="card shadow-sm border-0">
                                <div className="card-body text-center">
                                    <i className="fe fe-home mb-3" style={{ fontSize: '3rem', color: themeColor, opacity: 0.3 }}></i>
                                    <h3 className="font-weight-bold mb-1" style={{ color: themeColor }}>
                                        {bookedRooms}/{totalRooms}
                                    </h3>
                                    <p className="text-muted mb-2">{t.currentlyBookedRooms}</p>
                                    <div className={`badge ${occupancyRate >= 70 ? 'badge-success' : occupancyRate >= 50 ? 'badge-warning' : 'badge-danger'}`}>
                                        {occupancyRate}% {t.occupied}
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="col-lg-4 mb-4">
                            <div className="card shadow-sm border-0">
                                <div className="card-body">
                                    <h6 className="font-weight-bold mb-3">{t.quickStats}</h6>
                                    <div className="d-flex justify-content-between mb-2">
                                        <span className="text-muted">{t.eventRooms}:</span>
                                        <span className="font-weight-medium">{totalEventRooms}</span>
                                    </div>
                                    <div className="d-flex justify-content-between mb-2">
                                        <span className="text-muted">{t.services}:</span>
                                        <span className="font-weight-medium">{totalServices}</span>
                                    </div>
                                    <div className="d-flex justify-content-between mb-2">
                                        <span className="text-muted">{t.totalBookings}:</span>
                                        <span className="font-weight-medium">{totalBookings}</span>
                                    </div>
                                    <div className="d-flex justify-content-between">
                                        <span className="text-muted">{t.cancelled}:</span>
                                        <span className="font-weight-medium text-danger">{cancelledBookings}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Visualization Charts Row */}
                    <div className="row mb-4">
                        {/* Bookings by Category Pie Chart */}
                        <div className="col-lg-4 mb-4">
                            <div className="card shadow-sm border-0 h-100">
                                <div className="card-header bg-white border-bottom">
                                    <h5 className="mb-0 font-weight-bold">
                                        <i className="fe fe-pie-chart mr-2" style={{ color: themeColor }}></i>
                                        {t.bookingsByCategory}
                                    </h5>
                                </div>
                                <div className="card-body">
                                    {bookingsByCategory && bookingsByCategory.length > 0 ? (
                                        <div style={{ height: '300px', position: 'relative' }}>
                                            <canvas id="bookingsByCategoryChart"></canvas>
                                        </div>
                                    ) : (
                                        <p className="text-muted text-center mb-0">{t.noBookingData}</p>
                                    )}
                                </div>
                            </div>
                        </div>

                        {/* Booking Status Distribution */}
                        <div className="col-lg-4 mb-4">
                            <div className="card shadow-sm border-0 h-100">
                                <div className="card-header bg-white border-bottom">
                                    <h5 className="mb-0 font-weight-bold">
                                        <i className="fe fe-pie-chart mr-2" style={{ color: themeColor }}></i>
                                        {t.bookingStatus}
                                    </h5>
                                </div>
                                <div className="card-body">
                                    {statusDistribution && statusDistribution.length > 0 ? (
                                        <div style={{ height: '300px', position: 'relative' }}>
                                            <canvas id="statusDistributionChart"></canvas>
                                        </div>
                                    ) : (
                                        <p className="text-muted text-center mb-0">{t.noStatusData}</p>
                                    )}
                                </div>
                            </div>
                        </div>

                        {/* Revenue by Category Bar Chart */}
                        <div className="col-lg-4 mb-4">
                            <div className="card shadow-sm border-0 h-100">
                                <div className="card-header bg-white border-bottom">
                                    <h5 className="mb-0 font-weight-bold">
                                        <i className="fe fe-bar-chart mr-2" style={{ color: themeColor }}></i>
                                        {t.revenueByCategory}
                                    </h5>
                                </div>
                                <div className="card-body">
                                    {revenueByCategory && revenueByCategory.length > 0 ? (
                                        <div style={{ height: '300px', position: 'relative' }}>
                                            <canvas id="revenueByCategoryChart"></canvas>
                                        </div>
                                    ) : (
                                        <p className="text-muted text-center mb-0">{t.noRevenueData}</p>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Recent Bookings Table */}
                    <div className="row">
                        <div className="col-12">
                            <div className="card shadow-sm border-0">
                                <div className="card-header bg-white border-bottom d-flex justify-content-between align-items-center">
                                    <h5 className="mb-0 font-weight-bold">
                                        <i className="fe fe-list mr-2" style={{ color: themeColor }}></i>
                                        {t.recentBookings}
                                    </h5>
                                    <Link href="/admin/bookings" className="btn btn-sm btn-outline-primary">
                                        {t.viewAll}
                                    </Link>
                                </div>
                                <div className="card-body p-0">
                                    {recentBookings && recentBookings.length > 0 ? (
                                        <div className="table-responsive">
                                            <table className="table table-hover mb-0">
                                                <thead className="thead-light">
                                                    <tr>
                                                        <th>{t.reference}</th>
                                                        <th>{t.guestName}</th>
                                                        <th>{t.room}</th>
                                                        <th>{t.checkIn}</th>
                                                        <th>{t.checkOut}</th>
                                                        <th>{t.amount}</th>
                                                        <th>{t.status}</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    {recentBookings.map((booking) => (
                                                        <tr 
                                                            key={booking.id}
                                                            style={{ cursor: 'pointer' }}
                                                            onClick={() => handleBookingClick(booking)}
                                                            onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#f8f9fa'}
                                                            onMouseLeave={(e) => e.currentTarget.style.backgroundColor = ''}
                                                        >
                                                            <td>
                                                                <small className="font-weight-medium">#{booking.booking_reference}</small>
                                                            </td>
                                                            <td>{booking.full_name}</td>
                                                            <td>
                                                                <small className="text-muted">
                                                                    {booking.room || 'N/A'}
                                                                </small>
                                                            </td>
                                                            <td>
                                                                <small>
                                                                    {booking.check_in ? formatDate(booking.check_in) : 'N/A'}
                                                                </small>
                                                            </td>
                                                            <td>
                                                                <small>
                                                                    {booking.check_out ? formatDate(booking.check_out) : 'N/A'}
                                                                </small>
                                                            </td>
                                                            <td>
                                                                <small>
                                                                    USD {(booking.price_usd ?? booking.price ?? 0).toLocaleString(undefined, { minimumFractionDigits: 2 })}
                                                                    &nbsp;|&nbsp; BIF {booking.price_bif != null && booking.price_bif !== '' ? Number(booking.price_bif).toLocaleString() : '—'}
                                                                </small>
                                                            </td>
                                                            <td>
                                                                <span className={`badge ${
                                                                    booking.status === 'confirmed' ? 'badge-success' :
                                                                    booking.status === 'pending' ? 'badge-warning' :
                                                                    'badge-secondary'
                                                                }`}>
                                                                    {translateStatus(booking.status)}
                                                                </span>
                                                            </td>
                                                        </tr>
                                                    ))}
                                                </tbody>
                                            </table>
                                        </div>
                                    ) : (
                                        <div className="text-center py-5">
                                            <i className="fe fe-inbox mb-3" style={{ fontSize: '3rem', color: '#dee2e6' }}></i>
                                            <p className="text-muted mb-0">{t.noRecentBookings}</p>
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Booking Details Modal */}
            <ConfirmBooking 
                isOpen={isBookingModalOpen} 
                onClose={() => {
                    setIsBookingModalOpen(false);
                    setSelectedBooking(null);
                }}
                initialData={selectedBooking}
            />
        </div>
    );
}
