
import React, { useState, useMemo, useEffect } from 'react';
import { usePage, router } from '@inertiajs/react';
import {
    LayoutGrid, PackagePlus, Bike, CalendarCheck, ShoppingBag,
    Wallet, ShieldAlert, ReceiptText, MoveRight, Gavel,
    BarChart3, Coins, Landmark, Truck, Users, Settings,
    Repeat, CreditCard, AlertCircle, Share2, Briefcase
} from 'lucide-react';

import { Header, SidebarItem, Toast } from './CommonUI.tsx';
import { DashboardPage } from './DashboardPage.tsx';
import { ProductsPage } from './ProductsPage.tsx';
import { StockPage } from './StockPage.tsx';
import { BookingsPage } from './BookingsPage.tsx';
import { TerminalPage } from './TerminalPage.tsx';
import { ExpensesPage } from './ExpensesPage.tsx';
import { SuppliersPage } from './SuppliersPage.tsx';
import { CustomersPage } from './CustomersPage.tsx';
import { CapitalPage } from './CapitalPage.tsx';
import { RegistrationPage } from './RegistrationPage.tsx';
import { BikeTransferPage } from './BikeTransferPage.tsx';
import { ClaimsPage } from './ClaimsPage.tsx';
import { FeesPage } from './FeesPage.tsx';
import { SettingsPage } from './SettingsPage.tsx';
import { ReportsPage } from './ReportsPage.tsx';
import { AccountsManagementPage } from './AccountsManagementPage.tsx';
import { DealerExchangePage } from './DealerExchangePage.tsx';
import { InstallmentsPage } from './InstallmentsPage.tsx';
// import { ReportsDispatcherPage } from './ReportsDispatcherPage.tsx';
import BusinessAdvancesPage from './BusinessAdvancesPage.tsx'; // IMPORT

export const MENU_DEFINITIONS = [
    { id: 'dashboard', icon: LayoutGrid, label: 'Dashboard' },
    { id: 'products', icon: PackagePlus, label: 'Products' },
    { id: 'stock', icon: Bike, label: 'Stock' },
    { id: 'bookings', icon: CalendarCheck, label: 'Bookings' },
    { id: 'sales', icon: ShoppingBag, label: 'Sales' },
    { id: 'installments', icon: CreditCard, label: 'Lease' },
    { id: 'exchange', icon: Repeat, label: 'Exchanges' },
    { id: 'expenses', icon: Wallet, label: 'Expenses' },
    { id: 'advances', icon: Briefcase, label: 'B2B Loans' }, // NEW
    { id: 'claims', icon: ShieldAlert, label: 'Claims' },
    { id: 'fees', icon: ReceiptText, label: 'Fees' },
    { id: 'bike_transfer', icon: MoveRight, label: 'Transfers' },
    { id: 'registration', icon: Gavel, label: 'Registration' },
    { id: 'reports', icon: BarChart3, label: 'Reports' },
    { id: 'dispatcher', icon: Share2, label: 'AI Dispatch' },
    { id: 'capital', icon: Coins, label: 'Capital' },
    { id: 'accounts', icon: Landmark, label: 'Accounts' },
    { id: 'suppliers', icon: Truck, label: 'Suppliers' },
    { id: 'customers', icon: Users, label: 'Customers' },
    { id: 'settings', icon: Settings, label: 'Settings' },
];

export default function App() {
    const {
        auth = { user: { name: 'Admin', role: 'System' } }, // Default mock user
        products = [],
        customers = [],
        suppliers = [],
        accounts = [],
        physicalStock = [],
        purchaseOrders = [],
        salesHistory = [],
        bookings = [],
        expenses = [],
        capital = [],
        registrations = [],
        claims = [],
        feeBatches = [],
        workshops = [],
        transferInventory = [],
        transferHistory = [],
        dealerExchanges = [],
        vendorPayments = [],
        advances = [], // NEW PROP
        auditLogs = [],
        makes = [],
        years = [],
        colors = [],
        settings: initialSettings = { showroomName: 'MOTOAPP', hiddenModules: [] },
        flash = {},
        errors = {}
    }: any = usePage().props;

    const [activeItem, setActiveItem] = useState('dashboard');
    const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
    const [currentSettings, setCurrentSettings] = useState(initialSettings);
    const [requestedReport, setRequestedReport] = useState<string | null>(null);
    const [notification, setNotification] = useState<string | null>(null);

    // Sync settings when props change - FIX: Avoid circular dependency loop by checking stringified values
    useEffect(() => {
        setCurrentSettings((prev: any) => {
            if (JSON.stringify(prev) !== JSON.stringify(initialSettings)) {
                return initialSettings;
            }
            return prev;
        });
    }, [JSON.stringify(initialSettings)]);

    // Sync backend flash messages to local notification state - FIX: Depend only on the message string
    useEffect(() => {
        if (flash?.message) {
            setNotification(flash.message);
        }
    }, [flash?.message]);

    const visibleMenu = useMemo(() => {
        const hidden = currentSettings.hiddenModules || [];
        return MENU_DEFINITIONS.filter(m => !hidden.includes(m.id));
    }, [currentSettings.hiddenModules]);

    const stats = useMemo(() => {
        // Helper to handle both frontend camelCase and backend snake_case properties
        const getVal = (obj: any, keys: string[]) => {
            for (const key of keys) {
                if (obj[key] !== undefined && obj[key] !== null) {
                    return Number(obj[key]) || 0;
                }
            }
            return 0;
        };

        const totalRevenue = (salesHistory || []).reduce((a:number, s:any) => {
            return a + getVal(s, ['total', 'total_amount', 'totalPrice']);
        }, 0);

        const cashBalance = (accounts || []).reduce((a:number, acc:any) => {
            return a + (Number(acc.balance) || 0);
        }, 0);

        const stockCount = (physicalStock || []).length;

        const activeBookings = (bookings || []).filter((b: any) => b.status === 'Pending' || b.status === 'Confirmed').length;

        const grossProfit = (salesHistory || []).reduce((a:number, s:any) => {
            const total = getVal(s, ['total', 'total_amount', 'totalPrice']);
            const cost = getVal(s, ['costPrice', 'cost_price', 'purchasePrice', 'purchase_price']);
            return a + (total - cost);
        }, 0);

        return { totalRevenue, grossProfit, activeBookings, cashBalance, stockCount };
    }, [salesHistory, accounts, physicalStock, bookings]);

    // Unified Notification Handler
    const notify = (msg: string) => {
        setNotification(msg);
    };

    const commonProps = {
        products, customers, suppliers, accounts, physicalStock, purchaseOrders, salesHistory,
        bookings, expenses, capital, registrations, claims, feeBatches, workshops,
        transferInventory, transferHistory, dealerExchanges, vendorPayments, advances, // NEW
        logs: auditLogs,
        user: auth.user, showroomSettings: currentSettings, stats, errors,
        setActiveItem,
        notify,
        makes, years, colors,
        allModules: MENU_DEFINITIONS,
        requestedReport, setRequestedReport
    };

    const renderView = () => {
        switch(activeItem) {
            case 'dashboard': return <DashboardPage {...commonProps} />;
            case 'products': return <ProductsPage {...commonProps} />;
            case 'stock': return <StockPage {...commonProps} />;
            case 'bookings': return <BookingsPage {...commonProps} />;
            case 'sales': return <TerminalPage {...commonProps} />;
            case 'installments': return <InstallmentsPage {...commonProps} />;
            case 'expenses': return <ExpensesPage {...commonProps} />;
            case 'suppliers': return <SuppliersPage {...commonProps} />;
            case 'customers': return <CustomersPage {...commonProps} />;
            case 'capital': return <CapitalPage {...commonProps} />;
            case 'registration': return <RegistrationPage {...commonProps} />;
            case 'bike_transfer': return <BikeTransferPage {...commonProps} />;
            case 'claims': return <ClaimsPage {...commonProps} />;
            case 'fees': return <FeesPage {...commonProps} />;
            case 'accounts': return <AccountsManagementPage {...commonProps} />;
            case 'settings': return <SettingsPage {...commonProps} />;
            case 'reports': return <ReportsPage {...commonProps} />;
            case 'dispatcher': return <ReportsDispatcherPage {...commonProps} />;
            case 'exchange': return <DealerExchangePage {...commonProps} />;
            case 'advances': return <BusinessAdvancesPage {...commonProps} />; // NEW
            default: return <DashboardPage {...commonProps} />;
        }
    };

    return (
        <div className="min-h-screen bg-slate-50 flex">
            <nav className={`fixed top-0 left-0 bottom-0 w-[240px] bg-slate-950 flex flex-col z-[70] shadow-2xl transition-transform duration-300 ${isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full lg:translate-x-0'}`}>
                <div className="p-6 border-b border-white/5 flex items-center gap-3 shrink-0">
                    <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-cyan-400 to-blue-600 flex items-center justify-center text-white"><Bike size={20} /></div>
                    <div><h1 className="text-white font-bold font-logo text-sm uppercase italic tracking-tighter">{currentSettings.showroomName}</h1></div>
                </div>
                <div className="flex-1 p-3 space-y-0.5 overflow-y-auto custom-scrollbar">
                    {visibleMenu.map((item) => (
                        <SidebarItem key={item.id} item={item} isActive={activeItem === item.id} onClick={() => { setActiveItem(item.id); setIsMobileMenuOpen(false); }} />
                    ))}
                </div>
            </nav>

            <main className="flex-1 ml-0 lg:ml-[240px] transition-all duration-300 min-w-0 relative">
                <Header title={activeItem} onMenuClick={() => setIsMobileMenuOpen(true)} user={auth.user} onLogout={() => router.post('/logout')} setActiveItem={setActiveItem} />
                <div className="p-4 lg:p-6 max-w-[1440px] mx-auto">
                    {renderView()}
                </div>

                {/* Validation Errors Overlay */}
                {errors && Object.keys(errors).length > 0 && (
                    <div className="fixed bottom-6 right-6 z-[600] animate-slide-in-right bg-rose-600 text-white p-6 rounded-[2rem] shadow-2xl border-4 border-rose-500/50 max-w-sm">
                        <div className="flex items-center gap-3 mb-3 border-b border-white/20 pb-3">
                            <AlertCircle size={24} />
                            <h4 className="font-black uppercase text-xs tracking-widest">Entry Validation Failed</h4>
                        </div>
                        <ul className="space-y-1">
                            {Object.entries(errors).map(([key, msg]: any) => (
                                <li key={key} className="text-[10px] font-bold uppercase tracking-tight opacity-90">• {msg}</li>
                            ))}
                        </ul>
                        <button onClick={() => router.reload()} className="mt-4 w-full bg-white text-rose-600 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest hover:bg-rose-50 transition-colors">Clear Warnings</button>
                    </div>
                )}
            </main>

            {/* Global Success Notification */}
            {notification && <Toast message={notification} onClose={() => setNotification(null)} />}
        </div>
    );
}
