import React, { useState, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import {
    TrendingUp,
    TrendingDown,
    Wallet,
    Plus,
    MoreVertical,
    FileText,
    Repeat,
    ChevronDown,
    BarChart3,
    PieChart,
    Users,
    UserPlus,
    Receipt,
    Clock,
    Search,
    RefreshCw,
    AlertCircle
} from 'lucide-react';
import axios from 'axios';
import {
    LineChart,
    Line,
    XAxis,
    YAxis,
    CartesianGrid,
    Tooltip,
    ResponsiveContainer,
    AreaChart,
    Area,
    ReferenceLine,
    PieChart as RePieChart,
    Pie,
    Cell,
    Legend
} from 'recharts';
import { useAuth } from '../contexts/AuthContext';
import settingsService from '../services/settingsService';

import AddInvoiceModal from '../components/AddInvoiceModal';
import AddClientModal from '../components/AddClientModal';
import AddExpenseModal from '../components/AddExpenseModal';
import AddIncomeModal from '../components/AddIncomeModal';
import { Download, Calculator, DollarSign, Briefcase } from 'lucide-react';

const Dashboard = () => {
    const navigate = useNavigate();
    const { user } = useAuth();
    const [data, setData] = useState({
        incomeTotal: 0,
        expenseTotal: 0,
        recentExpenses: [],
        billing: { outstanding: 0, overdue: 0 },
        metrics: { mrr: 0, subscriptionCount: 0, bankBalance: 0 },
        allIncomes: [],
        allExpenses: []
    });
    const [loading, setLoading] = useState(true);
    const [currency, setCurrency] = useState('KES');
    const [companyName, setCompanyName] = useState('FinancePro');
    const [chartTimeframe, setChartTimeframe] = useState('monthly');

    const [showNewMenu, setShowNewMenu] = useState(false);

    // Modals
    const [showInvoiceModal, setShowInvoiceModal] = useState(false);
    const [showClientModal, setShowClientModal] = useState(false);
    const [showExpenseModal, setShowExpenseModal] = useState(false);
    const [showIncomeModal, setShowIncomeModal] = useState(false);

    useEffect(() => {
        const fetchStats = async () => {
            try {
                const token = localStorage.getItem('token');
                if (!token) return;
                const config = { headers: { Authorization: `Bearer ${token}` } };

                const [incomeSum, expenseSum, billingRes, metricRes, subRes, settingsRes, allIncomesRes, allExpensesRes] = await Promise.all([
                    axios.get('http://localhost:5000/api/income/summary', config),
                    axios.get('http://localhost:5000/api/expenses/summary', config),
                    axios.get('http://localhost:5000/api/billing/invoices', config),
                    axios.get('http://localhost:5000/api/reports/metrics', config),
                    axios.get('http://localhost:5000/api/subscriptions', config),
                    settingsService.getSettings(),
                    axios.get('http://localhost:5000/api/income', config),
                    axios.get('http://localhost:5000/api/expenses', config)
                ]);

                setCurrency(settingsRes.data.DEFAULT_CURRENCY || 'KES');
                setCompanyName(settingsRes.data.COMPANY_NAME || 'FinancePro');

                const invoices = billingRes.data || [];
                const outstanding = invoices.filter(i => i.status !== 'Paid' && i.status !== 'Cancelled').reduce((sum, i) => sum + Number(i.balanceDue), 0);
                const overdue = invoices.filter(i => i.status === 'Overdue').reduce((sum, i) => sum + Number(i.balanceDue), 0);

                setData({
                    incomeTotal: incomeSum.data?.total || 0,
                    expenseTotal: expenseSum.data?.total || 0,
                    recentExpenses: expenseSum.data?.recent || [],
                    billing: { outstanding, overdue },
                    metrics: {
                        mrr: metricRes.data?.mrr || 0,
                        bankBalance: metricRes.data?.bankBalance || 0,
                        subscriptionCount: subRes.data?.length || 0
                    },
                    allIncomes: allIncomesRes.data || [],
                    allExpenses: allExpensesRes.data || []
                });
            } catch (err) {
                console.error('Dashboard fetch error:', err);
            } finally {
                setLoading(false);
            }
        };
        fetchStats();
    }, []);

    // Process Chart Data
    const { processedData, hasData, categoryData } = useMemo(() => {
        const labels = [];
        const incomeValues = [];
        const expenseValues = [];
        let totalVal = 0;

        const today = new Date();
        const year = today.getFullYear();
        const month = today.getMonth();

        if (chartTimeframe === 'monthly') {
            const daysInMonth = new Date(year, month + 1, 0).getDate();
            const currentDay = today.getDate();

            for (let day = 1; day <= daysInMonth; day++) {
                const dateStr = new Date(year, month, day).toDateString();
                const income = data.allIncomes
                    .filter(inc => new Date(inc.receivedDate).toDateString() === dateStr)
                    .reduce((sum, inc) => sum + Number(inc.amount), 0);
                const expense = data.allExpenses
                    .filter(exp => new Date(exp.expenseDate).toDateString() === dateStr)
                    .reduce((sum, exp) => sum + Number(exp.amount), 0);

                labels.push(day.toString());
                incomeValues.push(income);
                expenseValues.push(expense);
                totalVal += (income + expense);
            }
        } else {
            // Last Month
            const prevMonth = new Date(year, month - 1, 1);
            const daysInPrevMonth = new Date(year, month, 0).getDate();
            const prevMonthYear = prevMonth.getFullYear();
            const prevMonthIndex = prevMonth.getMonth();

            for (let day = 1; day <= daysInPrevMonth; day++) {
                const dateStr = new Date(prevMonthYear, prevMonthIndex, day).toDateString();
                const income = data.allIncomes
                    .filter(inc => new Date(inc.receivedDate).toDateString() === dateStr)
                    .reduce((sum, inc) => sum + Number(inc.amount), 0);
                const expense = data.allExpenses
                    .filter(exp => new Date(exp.expenseDate).toDateString() === dateStr)
                    .reduce((sum, exp) => sum + Number(exp.amount), 0);

                labels.push(day.toString());
                incomeValues.push(income);
                expenseValues.push(expense);
                totalVal += (income + expense);
            }
        }

        // Category Data
        const cats = {};
        data.allExpenses.forEach(exp => {
            const catName = exp.ExpenseCategory?.name || 'Uncategorized';
            cats[catName] = (cats[catName] || 0) + Number(exp.amount);
        });
        const categoryData = Object.entries(cats).map(([name, value]) => ({ name, value }));

        return {
            processedData: labels.map((label, i) => ({
                name: label,
                Income: incomeValues[i],
                Expense: expenseValues[i]
            })),
            hasData: totalVal > 0,
            categoryData
        };
    }, [chartTimeframe, data.allIncomes, data.allExpenses]);

    const CustomTooltip = ({ active, payload, label }) => {
        if (active && payload && payload.length) {
            return (
                <div className="bg-white dark:bg-slate-900 p-4 border border-slate-100 dark:border-slate-800 rounded-2xl shadow-premium-deep">
                    <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2">Day {label}</p>
                    <div className="space-y-1">
                        <p className="text-xs font-black text-primary flex items-center justify-between gap-8">
                            <span>INCOME</span>
                            <span>{currency} {payload[0].value.toLocaleString()}</span>
                        </p>
                        <p className="text-xs font-black text-rose-500 flex items-center justify-between gap-8">
                            <span>EXPENSE</span>
                            <span>{currency} {payload[1].value.toLocaleString()}</span>
                        </p>
                    </div>
                </div>
            );
        }
        return null;
    };

    if (loading) {
        return (
            <div className="h-[60vh] flex flex-col items-center justify-center gap-4">
                <div className="w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"></div>
                <p className="text-slate-400 font-bold uppercase text-[10px] tracking-[0.3em]">Loading dashboard...</p>
            </div>
        );
    }

    const getGreeting = () => {
        const hour = new Date().getHours();
        if (hour < 12) return "Good morning";
        if (hour < 18) return "Good afternoon";
        return "Good evening";
    };

    const handleQuickAction = (action) => {
        setShowNewMenu(false);
        switch (action) {
            case 'invoice': setShowInvoiceModal(true); break;
            case 'client': setShowClientModal(true); break;
            case 'expense': setShowExpenseModal(true); break;
            case 'income': setShowIncomeModal(true); break;
            case 'quote': navigate('/quotes'); break;
            case 'user': navigate('/users'); break;
            case 'vendor': navigate('/vendors'); break;
            case 'staff': navigate('/staff'); break;
            default: break;
        }
    };

    return (
        <div className="space-y-10 animate-in fade-in slide-in-from-bottom-5 duration-1000 pb-20 max-w-[1700px] mx-auto transition-colors relative">

            {/* Modals */}
            <AddInvoiceModal isOpen={showInvoiceModal} onClose={() => setShowInvoiceModal(false)} onRefresh={() => window.location.reload()} />
            <AddClientModal isOpen={showClientModal} onClose={() => setShowClientModal(false)} onRefresh={() => window.location.reload()} />
            <AddExpenseModal isOpen={showExpenseModal} onClose={() => setShowExpenseModal(false)} onRefresh={() => window.location.reload()} />
            <AddIncomeModal isOpen={showIncomeModal} onClose={() => setShowIncomeModal(false)} onRefresh={() => window.location.reload()} />

            {/* Brand Header & Actions */}
            <div className="flex flex-col sm:flex-row justify-between items-end sm:items-center gap-6 mb-8">
                <div className="flex flex-col items-start justify-center">
                    <h1 className="text-2xl font-black text-slate-800 dark:text-white tracking-tight mb-1">
                        {companyName}
                    </h1>
                    <p className="text-sm font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest">
                        {getGreeting()}, <span className="text-primary">{user?.fullName?.split(' ')[0] || 'Member'}</span>
                    </p>
                </div>

                <div className="flex items-center gap-3 z-20">
                    <button className="flex items-center gap-2 px-5 py-2.5 bg-white dark:bg-bg-darkCard hover:bg-slate-50 dark:hover:bg-slate-800 border border-slate-200 dark:border-slate-800 rounded-xl transition-all text-xs font-black uppercase tracking-widest text-slate-500 hover:text-primary shadow-sm">
                        <Download className="w-4 h-4" />
                        <span className="hidden sm:inline">Report</span>
                    </button>

                    <div className="relative">
                        <button
                            onClick={() => setShowNewMenu(!showNewMenu)}
                            onBlur={() => setTimeout(() => setShowNewMenu(false), 200)}
                            className="flex items-center gap-2 px-6 py-2.5 bg-primary hover:bg-primary-dark text-white rounded-xl transition-all shadow-lg shadow-primary/30 active:scale-95 group"
                        >
                            <Plus className="w-4 h-4 group-hover:rotate-90 transition-transform duration-300" />
                            <span className="text-xs font-black uppercase tracking-widest">New</span>
                        </button>

                        {/* Dropdown Menu */}
                        <div className={`absolute right-0 top-full mt-2 w-56 bg-white dark:bg-bg-darkCard rounded-2xl shadow-premium-deep border border-slate-100 dark:border-slate-800 overflow-hidden transition-all duration-200 origin-top-right ${showNewMenu ? 'opacity-100 scale-100 visible' : 'opacity-0 scale-95 invisible'}`}>
                            <div className="p-2 space-y-1">
                                <div className="px-3 py-2 text-[10px] font-black text-slate-400 uppercase tracking-widest">Create New</div>
                                <button onClick={() => handleQuickAction('invoice')} className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors text-left group">
                                    <div className="p-1.5 bg-blue-50 text-blue-600 rounded-lg group-hover:bg-white"><FileText className="w-4 h-4" /></div>
                                    <span className="text-xs font-bold text-slate-700 dark:text-slate-200">Invoice</span>
                                </button>
                                <button onClick={() => handleQuickAction('quote')} className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors text-left group">
                                    <div className="p-1.5 bg-purple-50 text-purple-600 rounded-lg group-hover:bg-white"><Calculator className="w-4 h-4" /></div>
                                    <span className="text-xs font-bold text-slate-700 dark:text-slate-200">Estimate / Quote</span>
                                </button>
                                <button onClick={() => handleQuickAction('client')} className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors text-left group">
                                    <div className="p-1.5 bg-emerald-50 text-emerald-600 rounded-lg group-hover:bg-white"><UserPlus className="w-4 h-4" /></div>
                                    <span className="text-xs font-bold text-slate-700 dark:text-slate-200">Client</span>
                                </button>
                                <div className="h-px bg-slate-100 dark:bg-slate-800 my-1"></div>
                                <div className="px-3 py-2 text-[10px] font-black text-slate-400 uppercase tracking-widest">Finance</div>
                                <button onClick={() => handleQuickAction('income')} className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors text-left group">
                                    <div className="p-1.5 bg-green-50 text-green-600 rounded-lg group-hover:bg-white"><DollarSign className="w-4 h-4" /></div>
                                    <span className="text-xs font-bold text-slate-700 dark:text-slate-200">Record Income</span>
                                </button>
                                <button onClick={() => handleQuickAction('expense')} className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors text-left group">
                                    <div className="p-1.5 bg-rose-50 text-rose-600 rounded-lg group-hover:bg-white"><Wallet className="w-4 h-4" /></div>
                                    <span className="text-xs font-bold text-slate-700 dark:text-slate-200">Record Expense</span>
                                </button>
                                <div className="h-px bg-slate-100 dark:bg-slate-800 my-1"></div>
                                <div className="px-3 py-2 text-[10px] font-black text-slate-400 uppercase tracking-widest">Management</div>
                                <button onClick={() => handleQuickAction('user')} className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors text-left group">
                                    <div className="p-1.5 bg-orange-50 text-orange-600 rounded-lg group-hover:bg-white"><Users className="w-4 h-4" /></div>
                                    <span className="text-xs font-bold text-slate-700 dark:text-slate-200">User / Staff</span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            {/* Metrics Grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                {/* Net Profit - Blue Card */}
                <div className="bg-blue-500 rounded-[2rem] p-6 text-white shadow-xl shadow-blue-500/20 relative overflow-hidden group">
                    <div className="absolute top-0 right-0 p-6 opacity-10">
                        <Wallet className="w-16 h-16 transform group-hover:scale-110 transition-transform duration-500" />
                    </div>
                    <div className="relative z-10">
                        <div className="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center backdrop-blur-sm mb-6">
                            <Wallet className="w-5 h-5 text-white" />
                        </div>
                        <p className="text-[10px] font-black opacity-80 uppercase tracking-widest mb-1">Net Profit</p>
                        <h3 className="text-2xl font-extrabold tracking-tight">
                            {currency} {(Number(data.incomeTotal) - Number(data.expenseTotal)).toLocaleString()}
                        </h3>
                    </div>
                </div>

                {/* Total Income */}
                <div className="bg-white dark:bg-bg-darkCard rounded-[2rem] p-6 shadow-sm border border-slate-100 dark:border-slate-800 group hover:shadow-md transition-all">
                    <div className="w-10 h-10 bg-emerald-50 dark:bg-emerald-500/10 rounded-xl flex items-center justify-center mb-6">
                        <TrendingUp className="w-5 h-5 text-emerald-500" />
                    </div>
                    <p className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest mb-1">Total Income</p>
                    <h3 className="text-2xl font-extrabold text-slate-800 dark:text-white tracking-tight">
                        {currency} {Number(data.incomeTotal).toLocaleString()}
                    </h3>
                </div>

                {/* Total Expenses */}
                <div className="bg-white dark:bg-bg-darkCard rounded-[2rem] p-6 shadow-sm border border-slate-100 dark:border-slate-800 group hover:shadow-md transition-all">
                    <div className="w-10 h-10 bg-rose-50 dark:bg-rose-500/10 rounded-xl flex items-center justify-center mb-6">
                        <TrendingDown className="w-5 h-5 text-rose-500" />
                    </div>
                    <p className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest mb-1">Total Expenses</p>
                    <h3 className="text-2xl font-extrabold text-slate-800 dark:text-white tracking-tight">
                        {currency} {Number(data.expenseTotal).toLocaleString()}
                    </h3>
                </div>

                {/* Outstanding */}
                <div className="bg-white dark:bg-bg-darkCard rounded-[2rem] p-6 shadow-sm border border-slate-100 dark:border-slate-800 group hover:shadow-md transition-all">
                    <div className="w-10 h-10 bg-amber-50 dark:bg-amber-500/10 rounded-xl flex items-center justify-center mb-6">
                        <FileText className="w-5 h-5 text-amber-500" />
                    </div>
                    <p className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest mb-1">Outstanding</p>
                    <h3 className="text-2xl font-extrabold text-slate-800 dark:text-white tracking-tight">
                        {currency} {Number(data.billing.outstanding).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                    </h3>
                </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                {/* Performance Overview Chart */}
                <div className="premium-card p-6 sm:p-10 lg:col-span-2 flex flex-col">
                    <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-6 mb-8 sm:mb-12">
                        <div>
                            <h3 className="text-xl sm:text-2xl font-extrabold text-slate-800 dark:text-white tracking-tight">Revenue & Expenses</h3>
                            <p className="text-slate-400 dark:text-slate-500 font-bold text-[9px] sm:text-[10px] mt-1.5 uppercase tracking-widest pl-0.5">
                                {chartTimeframe === 'monthly' ? 'Monthly view' : 'Last month view'}
                            </p>
                        </div>
                        <div className="flex bg-slate-50 dark:bg-slate-900 p-1 rounded-2xl border border-slate-100 dark:border-slate-800 shadow-inner w-full sm:w-auto overflow-hidden">
                            <button
                                onClick={() => setChartTimeframe('monthly')}
                                className={`flex-1 sm:flex-none px-4 sm:px-6 py-2.5 text-[10px] sm:text-[11px] font-black transition-all uppercase tracking-widest rounded-xl ${chartTimeframe === 'monthly' ? 'text-primary bg-white dark:bg-bg-darkCard shadow-premium' : 'text-slate-400 dark:text-slate-500 hover:text-primary'}`}
                            >
                                Current
                            </button>
                            <button
                                onClick={() => setChartTimeframe('last_month')}
                                className={`flex-1 sm:flex-none px-4 sm:px-6 py-2.5 text-[10px] sm:text-[11px] font-black transition-all uppercase tracking-widest rounded-xl ${chartTimeframe === 'last_month' ? 'text-primary bg-white dark:bg-bg-darkCard shadow-premium' : 'text-slate-400 dark:text-slate-500 hover:text-primary'}`}
                            >
                                Previous
                            </button>
                        </div>
                    </div>

                    <div className="flex-1 h-64 sm:h-96 w-full sm:-ml-8">
                        {hasData ? (
                            <ResponsiveContainer width="100%" height="100%">
                                <AreaChart data={processedData}>
                                    <defs>
                                        <linearGradient id="colorIncome" x1="0" y1="0" x2="0" y2="1">
                                            <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3} />
                                            <stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
                                        </linearGradient>
                                        <linearGradient id="colorExpense" x1="0" y1="0" x2="0" y2="1">
                                            <stop offset="5%" stopColor="#f43f5e" stopOpacity={0.3} />
                                            <stop offset="95%" stopColor="#f43f5e" stopOpacity={0} />
                                        </linearGradient>
                                    </defs>
                                    <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#e2e8f0" opacity={0.5} />
                                    <XAxis
                                        dataKey="name"
                                        axisLine={false}
                                        tickLine={false}
                                        tick={{ fill: '#94a3b8', fontSize: 10, fontWeight: 900 }}
                                        dy={15}
                                    />
                                    <YAxis
                                        hide={true}
                                        domain={[0, 'auto']}
                                    />
                                    <Tooltip content={<CustomTooltip />} cursor={{ stroke: '#3b82f6', strokeWidth: 1, strokeDasharray: '5 5' }} />
                                    <Area
                                        type="monotone"
                                        dataKey="Income"
                                        stroke="#3b82f6"
                                        strokeWidth={4}
                                        fillOpacity={1}
                                        fill="url(#colorIncome)"
                                        animationDuration={2000}
                                    />
                                    <Area
                                        type="monotone"
                                        dataKey="Expense"
                                        stroke="#f43f5e"
                                        strokeWidth={4}
                                        fillOpacity={1}
                                        fill="url(#colorExpense)"
                                        animationDuration={2000}
                                    />
                                </AreaChart>
                            </ResponsiveContainer>
                        ) : (
                            <div className="h-full flex flex-col items-center justify-center text-center space-y-6 ml-8">
                                <div className="p-8 bg-slate-50 dark:bg-bg-dark rounded-[32px] text-slate-300 dark:text-slate-700 shadow-inner border border-slate-100 dark:border-slate-800/50">
                                    <BarChart3 className="w-16 h-16 animate-pulse" />
                                </div>
                                <div>
                                    <p className="text-slate-500 dark:text-slate-400 font-black uppercase text-xs tracking-[0.2em]">No data available</p>
                                    <p className="text-slate-400 dark:text-slate-600 text-[11px] font-bold mt-2">Add transactions to see your charts here</p>
                                </div>
                            </div>
                        )}
                    </div>
                </div>

                {/* Expenses by Category Widget */}
                <div className="premium-card p-6 sm:p-10 flex flex-col h-full">
                    <h3 className="text-xl font-extrabold text-slate-800 dark:text-white tracking-tight mb-8">Expense Breakdown</h3>
                    <div className="flex-1 min-h-[300px] w-full">
                        {categoryData.length > 0 ? (
                            <ResponsiveContainer width="100%" height="100%">
                                <RePieChart>
                                    <Pie
                                        data={categoryData}
                                        cx="50%"
                                        cy="50%"
                                        innerRadius={60}
                                        outerRadius={80}
                                        paddingAngle={5}
                                        dataKey="value"
                                    >
                                        {categoryData.map((entry, index) => (
                                            <Cell
                                                key={`cell-${index}`}
                                                fill={[
                                                    '#3b82f6', '#f43f5e', '#10b981', '#f59e0b',
                                                    '#8b5cf6', '#06b6d4', '#ec4899', '#64748b'
                                                ][index % 8]}
                                            />
                                        ))}
                                    </Pie>
                                    <Tooltip
                                        contentStyle={{
                                            backgroundColor: 'rgba(255, 255, 255, 0.9)',
                                            borderRadius: '1rem',
                                            border: 'none',
                                            boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1)'
                                        }}
                                        itemStyle={{ fontSize: '12px', fontWeight: 'bold' }}
                                    />
                                    <Legend
                                        verticalAlign="bottom"
                                        height={36}
                                        iconType="circle"
                                        formatter={(value) => <span className="text-[10px] font-black uppercase tracking-widest text-slate-500">{value}</span>}
                                    />
                                </RePieChart>
                            </ResponsiveContainer>
                        ) : (
                            <div className="h-full flex flex-col items-center justify-center opacity-40">
                                <PieChart className="w-12 h-12 mb-4" />
                                <p className="text-[10px] font-black uppercase tracking-widest text-center">No categorized<br />expenses found</p>
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* Bottom Widgets */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                <div className="premium-card p-8 flex items-center justify-between group overflow-hidden">
                    <div className="relative z-10">
                        <p className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest mb-1.5">Subscriptions</p>
                        <h4 className="text-4xl font-extrabold text-slate-800 dark:text-white">{data.metrics.subscriptionCount}</h4>
                        <span className="text-[10px] font-bold text-emerald-500 mt-2 block uppercase tracking-tighter">Active</span>
                    </div>
                    <div className="bg-primary/5 p-6 rounded-3xl group-hover:scale-125 group-hover:bg-primary/10 transition-all duration-500 shrink-0">
                        <Repeat className="w-8 h-8 sm:w-10 sm:h-10 text-primary opacity-40 group-hover:opacity-100 transition-opacity" />
                    </div>
                </div>

                <div className="premium-card p-8 flex items-center justify-between group overflow-hidden">
                    <div className="relative z-10">
                        <p className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest mb-1.5">Monthly Revenue (MRR)</p>
                        <h4 className="text-2xl sm:text-3xl font-extrabold text-slate-800 dark:text-white flex items-baseline">
                            <span className="text-slate-400 text-lg mr-1 font-medium">{currency}</span>
                            <span className="truncate">{Number(data.metrics.mrr).toLocaleString()}</span>
                        </h4>
                        <span className="text-[10px] font-bold text-primary mt-2 block uppercase tracking-tighter">Total Revenue</span>
                    </div>
                    <div className="bg-indigo-500/5 p-6 rounded-3xl group-hover:scale-125 group-hover:bg-indigo-500/10 transition-all duration-500 shrink-0">
                        <RefreshCw className="w-8 h-8 sm:w-10 sm:h-10 text-indigo-500 opacity-40 group-hover:opacity-100 transition-opacity" />
                    </div>
                </div>

                <div className="premium-card p-6 sm:p-8 flex flex-col justify-between overflow-hidden md:col-span-2 lg:col-span-1">
                    <div className="flex justify-between items-center mb-8">
                        <h3 className="text-lg font-extrabold text-slate-800 dark:text-white tracking-tight">Recent Activity</h3>
                        <button onClick={() => navigate('/expenses')} className="text-[10px] font-black text-primary hover:text-primary-dark uppercase tracking-widest transition-colors whitespace-nowrap">View all</button>
                    </div>
                    <div className="space-y-4">
                        {data.recentExpenses.length > 0 ? (
                            data.recentExpenses.slice(0, 3).map((exp) => (
                                <div key={exp.id} className="flex justify-between items-center p-4 bg-slate-50/50 dark:bg-bg-dark/50 hover:bg-slate-100 dark:hover:bg-bg-dark rounded-2xl transition-all cursor-pointer group">
                                    <div className="flex items-center gap-4 min-w-0">
                                        <div className="w-10 h-10 bg-white dark:bg-bg-darkCard rounded-xl flex items-center justify-center font-black text-slate-400 dark:text-slate-600 shadow-sm border border-slate-100 dark:border-slate-800 shrink-0 group-hover:border-primary/20 transition-colors">
                                            {exp.ExpenseCategory?.name?.charAt(0) || 'E'}
                                        </div>
                                        <div className="min-w-0">
                                            <p className="text-[13px] font-bold text-slate-700 dark:text-slate-200 truncate">{exp.Vendor?.name || 'General Expense'}</p>
                                            <p className="text-[9px] font-bold text-slate-400 uppercase tracking-widest mt-0.5 truncate">{exp.ExpenseCategory?.name || 'Uncategorized'}</p>
                                        </div>
                                    </div>
                                    <p className="text-[13px] font-black text-rose-500 shrink-0 ml-3">-{Number(exp.amount).toLocaleString()}</p>
                                </div>
                            ))
                        ) : (
                            <div className="py-8 text-center bg-slate-50/50 dark:bg-bg-dark/50 rounded-2xl">
                                <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest">No Recent Activity</p>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Dashboard;
