import React, { useState, useEffect } from 'react';
// Header and SubHeader are now part of the global Layout
import { 
    Wallet, 
    TrendingUp, 
    ArrowUpRight, 
    ArrowDownRight, 
    DollarSign,
    Activity,
    ShoppingCart,
    Package,
    AlertTriangle,
    Plus,
    History
} from 'lucide-react';

export default function ReceptionistDashboard() {
    const [stats, setStats] = useState({
        total_income: 0,
        total_expenses: 0,
        net_profit: 0,
        low_stock_count: 0
    });
    const [transactions, setTransactions] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const fetchDashboardData = async () => {
            try {
                const response = await fetch('/api/reports/profit');
                const data = await response.json();
                
                setStats({
                    total_income: data.total_income || 0,
                    total_expenses: data.total_expense || 0,
                    net_profit: data.net_profit || 0,
                    low_stock_count: data.low_stock_count || 0
                });
                setTransactions(data.transactions || []);
            } catch (error) {
                console.error('Error fetching dashboard data:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchDashboardData();
    }, []);

    const StatCard = ({ title, amount, icon: Icon, color, trend, iconColor, bgColor, textColor, label }) => (
        <div className={`${bgColor} p-6 rounded-[1.5rem] shadow-sm relative overflow-hidden group`}>
            <div className={`absolute top-0 right-0 w-24 h-24 bg-white/10 rounded-full -mr-8 -mt-8 transition-transform group-hover:scale-110`} />
            <div className="flex justify-between items-start mb-6 relative z-10">
                <div className={`p-3 rounded-xl bg-white/20 text-white shadow-sm`}>
                    <Icon size={20} />
                </div>
                {trend && (
                    <div className="flex items-center gap-1 px-2.5 py-1 rounded-full bg-white/20 text-white text-[10px] font-black uppercase tracking-wider">
                        {trend >= 0 ? <Plus size={10} /> : ''}
                        {trend}%
                    </div>
                )}
                {label && (
                    <div className="flex items-center gap-1 px-2.5 py-1 rounded-full bg-white/20 text-white text-[10px] font-black uppercase tracking-wider">
                        {label}
                    </div>
                )}
            </div>
            <div className="relative z-10 text-white">
                <h3 className="text-3xl font-black tracking-tight mb-1">
                    {(amount || 0).toLocaleString('en-AE', { minimumFractionDigits: 0 })}
                    <span className="text-sm font-bold ml-1.5 uppercase">{title === 'Low Stock Items' ? '' : 'AED'}</span>
                </h3>
                <p className="text-xs font-bold uppercase tracking-widest opacity-80">{title}</p>
            </div>
        </div>
    );

    const QuickAction = ({ icon: Icon, label, color, sublabel, path }) => (
        <button 
            onClick={() => path && (window.location.href = path)}
            className={`${color} p-6 rounded-[1.5rem] flex flex-col items-center justify-center gap-4 transition-all hover:scale-[1.02] shadow-sm border border-transparent hover:border-black/5 group`}
        >
            <div className={`p-4 rounded-full bg-white shadow-sm transition-transform group-hover:rotate-12`}>
                <Icon size={28} />
            </div>
            <div className="text-center">
                <span className="block text-sm font-black text-gray-900 uppercase tracking-widest leading-none mb-1">{label}</span>
                {sublabel && <span className="text-[10px] font-bold text-gray-400 uppercase tracking-tighter">{sublabel}</span>}
            </div>
        </button>
    );

    if (loading) {
        return (
            <div className="min-h-screen bg-[#FDFDFD] flex items-center justify-center">
                <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-red-500"></div>
            </div>
        );
    }

    return (
        <div className="animate-in fade-in duration-700">

            <main className="p-8 max-w-[1600px] mx-auto space-y-12 animate-in fade-in duration-700">
                {/* Welcome Section */}
                <div className="flex flex-col gap-2">
                    <h1 className="text-4xl font-black text-gray-900 tracking-tight flex items-center gap-4">
                        Receptionist Dashboard
                    </h1>
                </div>

                {/* Stats Grid */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
                    <StatCard 
                        title="Today's Sales" 
                        amount={stats.total_income} 
                        icon={DollarSign} 
                        bgColor="bg-[#22C55E]" 
                        trend={5}
                    />
                    <StatCard 
                        title="Monthly Expenses" 
                        amount={stats.total_expenses} 
                        icon={TrendingUp} 
                        bgColor="bg-[#EF4444]" 
                        trend={-2}
                    />
                    <StatCard 
                        title="Low Stock Items" 
                        amount={stats.low_stock_count} 
                        icon={AlertTriangle} 
                        bgColor="bg-[#F97316]" 
                        label="Action Needed"
                    />
                </div>

                {/* Quick Actions */}
                <div className="space-y-6">
                    <h2 className="text-xl font-black text-gray-900 uppercase tracking-widest ml-1">Quick Actions</h2>
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-8">
                        <QuickAction 
                            icon={ShoppingCart} 
                            label="New Sale (POS)" 
                            color="bg-[#F0FDF4] text-[#22C55E]" 
                            path="/receptionist/pos"
                        />
                        <QuickAction 
                            icon={TrendingUp} 
                            label="Add Expense" 
                            color="bg-[#FEF2F2] text-[#EF4444]" 
                            path="/receptionist/expenses"
                        />
                        <QuickAction 
                            icon={Package} 
                            label="Check Stock" 
                            color="bg-[#FFF7ED] text-[#F97316]" 
                            path="/receptionist/inventory"
                        />
                        <QuickAction 
                            icon={DollarSign} 
                            label="View Collections" 
                            color="bg-[#EFF6FF] text-[#3B82F6]" 
                            path="/receptionist/collections"
                        />
                    </div>
                </div>

                {/* Recent Transactions Table */}
                <div className="bg-white rounded-[2.5rem] border border-gray-100 shadow-sm overflow-hidden">
                    <div className="p-8 border-b border-gray-50 flex items-center justify-between bg-gray-50/10">
                        <div className="flex items-center gap-3">
                            <div className="p-2 bg-gray-100 rounded-xl">
                                <Activity size={18} className="text-gray-900" />
                            </div>
                            <h2 className="text-base font-black text-gray-900 uppercase tracking-widest">Recent Transactions</h2>
                        </div>
                    </div>
                    <div className="overflow-x-auto">
                        <table className="w-full text-left border-collapse">
                            <thead>
                                <tr className="bg-gray-50/50">
                                    <th className="px-8 py-5 text-[10px] font-black text-gray-400 uppercase tracking-[0.2em]">Date & Time</th>
                                    <th className="px-8 py-5 text-[10px] font-black text-gray-400 uppercase tracking-[0.2em]">Description</th>
                                    <th className="px-8 py-5 text-[10px] font-black text-gray-400 uppercase tracking-[0.2em]">Type</th>
                                    <th className="px-8 py-5 text-right text-[10px] font-black text-gray-400 uppercase tracking-[0.2em]">Amount</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-50">
                                {transactions.length > 0 ? (
                                    transactions.map((tx, idx) => (
                                        <tr key={idx} className="hover:bg-gray-50/30 transition-colors">
                                            <td className="px-8 py-5">
                                                <div className="flex flex-col">
                                                    <span className="text-sm font-bold text-gray-900">{tx.date}</span>
                                                    <span className="text-[10px] text-gray-400 font-medium uppercase tracking-tight">{tx.time}</span>
                                                </div>
                                            </td>
                                            <td className="px-8 py-5">
                                                <p className="text-sm font-bold text-gray-900">{tx.description}</p>
                                            </td>
                                            <td className="px-8 py-5">
                                                <span className={`px-2.5 py-1 rounded-full text-[10px] font-black shadow-sm uppercase tracking-wider ${
                                                    tx.debit > 0 ? 'bg-red-50 text-red-600' : 'bg-emerald-50 text-emerald-600'
                                                }`}>
                                                    {tx.debit > 0 ? 'DEBITED' : 'RECEIVED'}
                                                </span>
                                            </td>
                                            <td className="px-8 py-5 text-right">
                                                <span className={`text-sm font-black ${tx.debit > 0 ? 'text-red-500' : 'text-emerald-500'}`}>
                                                    {tx.debit > 0 ? '-' : '+'}
                                                    {(tx.debit || tx.credit || 0).toLocaleString('en-AE', { minimumFractionDigits: 2 })}
                                                    <span className="text-[10px] ml-1 uppercase">AED</span>
                                                </span>
                                            </td>
                                        </tr>
                                    ))
                                ) : (
                                    <tr>
                                        <td colSpan="4" className="px-8 py-20 text-center">
                                            <div className="flex flex-col items-center gap-4 text-gray-300">
                                                <div className="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center">
                                                    <Activity size={32} />
                                                </div>
                                                <p className="text-sm font-bold uppercase tracking-widest">No transactions found</p>
                                            </div>
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </main>
        </div>
    );
}
