import React, { useState, useEffect } from 'react';
import { usePage, Link, router } from '@inertiajs/react';
import axios from 'axios';
import { 
    Menu, User, ShoppingBag, Store, 
    MessageSquare, ClipboardList, Settings, PieChart, 
    Package, Heart, RefreshCw, LogOut, ArrowLeft,
    Sun, Moon, MapPin, Languages 
} from 'lucide-react';
import { Button } from "@/Components/ui/button";
import { ThemeProvider, useTheme } from "@/Components/ThemeProvider";
// --- FIX: Imported SheetTitle and SheetDescription ---
import { Sheet, SheetContent, SheetTrigger, SheetTitle, SheetDescription } from "@/Components/ui/sheet";
import { Avatar, AvatarFallback, AvatarImage } from "@/Components/ui/avatar";
import { Separator } from "@/Components/ui/separator";
import { ScrollArea } from "@/Components/ui/scroll-area";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/Components/ui/dropdown-menu";
import { useTranslation } from '@/hooks/useTranslation';
import NotificationDropdown from '@/Components/NotificationDropdown';

// --- THEME TOGGLE COMPONENT ---
function ThemeToggle() {
    const { theme, setTheme } = useTheme();
    return (
        <Button
            variant="ghost"
            size="icon"
            onClick={() => setTheme(theme === "light" ? "dark" : "light")}
            className="rounded-full shrink-0"
        >
            {theme === "light" ? (
                <Moon className="h-[1.2rem] w-[1.2rem]" />
            ) : (
                <Sun className="h-[1.2rem] w-[1.2rem]" />
            )}
            <span className="sr-only">Toggle theme</span>
        </Button>
    );
}

// --- SIDEBAR COMPONENT ---
function DashboardSidebar({ mode, unreadCount }) {
    const { t } = useTranslation(); 

    const buyerLinks = [
        { label: t('Overview'), routeName: 'dashboard.buyer', activePattern: 'dashboard.buyer', icon: PieChart },
        { label: t('My Orders'), routeName: 'buyer.orders.index', activePattern: 'buyer.orders.*', icon: ClipboardList }, 
        { label: t('Messages'), routeName: 'chat.index', activePattern: 'chat.*', icon: MessageSquare },  
        { label: t('Favorites'), routeName: 'buyer.favorites.index', activePattern: 'buyer.favorites.*', icon: Heart },
        { label: t('Address Book'), routeName: 'buyer.addresses.index', activePattern: 'buyer.addresses.*', icon: MapPin },
        { label: t('Account Settings'), routeName: 'settings.profile', activePattern: 'settings.*', icon: Settings },
    ];

    const sellerLinks = [
        { label: t('Shop Analytics'), routeName: 'dashboard.seller', activePattern: 'dashboard.seller', icon: PieChart },
        { label: t('Manage Products'), routeName: 'seller.products.index', activePattern: 'seller.products.*', icon: Package },
        { label: t('Company Profile'), routeName: 'seller.store-profile.edit', activePattern: 'seller.store-profile.*', icon: Store },
        { label: t('Received Orders'), routeName: 'seller.orders.index', activePattern: 'seller.orders.*', icon: ClipboardList }, 
        { label: t('Customer Messages'), routeName: 'chat.index', activePattern: 'chat.*', icon: MessageSquare }, 
        { label: t('Settings'), routeName: 'settings.profile', activePattern: 'settings.*', icon: Settings },
    ];

    const navItems = mode === 'seller' ? sellerLinks : buyerLinks;

    return (
        <div className="flex flex-col h-full py-4">
            <div className="px-6 mb-6">
                <Link href={route('home')} className="flex items-center gap-2 text-xl font-bold tracking-tight hover:opacity-80 transition-opacity shrink-0 h-7">
                    <ArrowLeft className="w-5 h-5 text-muted-foreground rtl:rotate-180" /> 
                    <span className="truncate">{t('Back to Market')}</span>
                </Link>
            </div>
            
            <div className="px-6 mb-4 h-6">
                <div className={`text-xs font-bold uppercase tracking-wider ${mode === 'seller' ? 'text-blue-500' : 'text-primary'}`}>
                    {mode === 'seller' ? t('Seller Hub') : t('Buyer Dashboard')}
                </div>
            </div>

            <ScrollArea className="flex-1 px-3">
                <nav className="space-y-1">
                    {navItems.map((item) => {
                        const isActive = item.activePattern 
                            ? route().current(item.activePattern) 
                            : route().current(item.routeName);
                        
                        return (
                            <Link
                                key={item.label}
                                href={route(item.routeName)}
                                className={`flex items-center justify-between px-3 py-2 text-sm font-medium transition-colors rounded-md outline-none ${
                                    isActive 
                                        ? 'bg-primary/10 text-primary font-semibold' 
                                        : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
                                }`}
                            >
                                <div className="flex items-center gap-3">
                                    <item.icon className={`w-4 h-4 shrink-0 ${isActive ? 'text-primary' : ''}`} />
                                    {item.label}
                                </div>

                                {item.routeName === 'chat.index' && unreadCount > 0 && (
                                    <span className="bg-blue-500 text-white text-[10px] w-5 h-5 flex items-center justify-center rounded-full font-bold shadow-sm shrink-0">
                                        {unreadCount > 99 ? '99+' : unreadCount}
                                    </span>
                                )}
                            </Link>
                        );
                    })}
                </nav>
            </ScrollArea>

            <div className="px-3 mt-auto shrink-0">
                <Separator className="my-4" />
                <Link 
                    href={route('logout')} 
                    method="post" 
                    as="button" 
                    className="flex items-center w-full gap-3 px-3 py-2 text-sm font-medium text-destructive transition-colors rounded-md hover:bg-destructive/10 text-start outline-none border-none bg-transparent"
                >
                    <LogOut className="w-4 h-4 shrink-0 rtl:rotate-180" />
                    {t('Logout')}
                </Link>
            </div>
        </div>
    );
}

// --- MAIN LAYOUT COMPONENT ---
export default function DashboardLayout({ children, mode = 'buyer' }) {
    const { auth, availableLanguages = [], locale, unreadMessagesCount, unreadNotificationsCount } = usePage().props;
    const { t, isRtl } = useTranslation(); 
    const user = auth?.user;
    
    const [open, setOpen] = useState(false);
    const [localUnreadCount, setLocalUnreadCount] = useState(unreadMessagesCount || 0);

    // 1. STRICT ROLE CHECK: Prevents layout flashing for standard buyers
    const canSell = user && ['seller', 'admin', 'manager'].includes(user.role);
    
    // 2. ENFORCE ACTIVE MODE: If the user is strictly a buyer, instantly force the buyer layout
    const activeMode = canSell ? mode : 'buyer';

    const toggleMode = () => {
        if (activeMode === 'buyer') {
            router.get(route('dashboard.seller'));
        } else {
            router.get(route('dashboard.buyer'));
        }
    };

    // Sync state when Inertia navigation happens
    useEffect(() => {
        setLocalUnreadCount(unreadMessagesCount);
    }, [unreadMessagesCount]);

    // --- WEB-SOCKET & 10-SECOND POLLING ENGINE ---
    useEffect(() => {
        if (!auth?.user) return;

        let pollInterval;

        const fetchUnreadCount = async () => {
            try {
                const res = await axios.get(route('chat.unread'));
                setLocalUnreadCount(res.data.unread_count);
            } catch (e) {}
        };

        const startPolling = () => {
            if (!pollInterval) {
                pollInterval = setInterval(fetchUnreadCount, 10000); 
            }
        };

        const stopPolling = () => {
            if (pollInterval) {
                clearInterval(pollInterval);
                pollInterval = null;
            }
        };

        if (window.Echo && window.Echo.connector.pusher) {
            const connection = window.Echo.connector.pusher.connection;
            
            window.Echo.private(`user.${auth.user.id}`)
                .listen('MessageSent', () => fetchUnreadCount());

            connection.bind('state_change', (states) => {
                if (states.current === 'unavailable' || states.current === 'disconnected') {
                    startPolling();
                } else if (states.current === 'connected') {
                    stopPolling(); 
                }
            });

            connection.bind('error', () => startPolling());
            
            if (connection.state !== 'connected') startPolling();
        } else {
            startPolling();
        }

        return () => {
            stopPolling();
            if (window.Echo) {
                window.Echo.leave(`user.${auth.user.id}`);
            }
        };
    }, [auth?.user]);

    return (
        <ThemeProvider defaultTheme="system" storageKey="app-ui-theme">
            <div className="flex min-h-screen bg-muted/20 text-foreground transition-colors duration-300">
                {/* Desktop Sidebar */}
                <aside className="fixed inset-y-0 start-0 hidden w-64 border-e bg-card lg:block shadow-sm z-20">
                    <DashboardSidebar mode={activeMode} unreadCount={localUnreadCount} />
                </aside>

                {/* Main Content Wrapper */}
                <div className="flex flex-col flex-1 lg:ps-64 min-w-0">
                    {/* Top Header */}
                    <header className="sticky top-0 z-30 flex items-center justify-between h-16 px-4 border-b bg-card/95 backdrop-blur shadow-sm">
                        <div className="flex items-center gap-4">
                            
                            <Sheet open={open} onOpenChange={setOpen}>
                                <SheetTrigger className="lg:hidden shrink-0 flex items-center justify-center w-10 h-10 rounded-md hover:bg-muted transition-colors outline-none text-foreground">
                                    <Menu className="w-5 h-5" />
                                </SheetTrigger>
                                <SheetContent side={isRtl ? 'right' : 'left'} className="w-64 p-0">
                                    {/* --- FIX: ADDED SR-ONLY TITLE AND DESCRIPTION --- */}
                                    <SheetTitle className="sr-only">{t('Navigation Menu')}</SheetTitle>
                                    <SheetDescription className="sr-only">{t('Access dashboard links')}</SheetDescription>
                                    <DashboardSidebar mode={activeMode} unreadCount={localUnreadCount} />
                                </SheetContent>
                            </Sheet>

                            {/* Fixed width title to prevent layout shifting when text changes */}
                            <h2 className="text-sm font-semibold lg:text-base hidden sm:block min-w-[140px] truncate">
                                {activeMode === 'seller' ? t('Seller Center') : t('My Dashboard')}
                            </h2>
                        </div>

                        <div className="flex items-center gap-2 sm:gap-4 shrink-0">
                            
                            {/* --- CONDITIONAL SWITCHER --- */}
                            {canSell && (
                                <>
                                    {/* Desktop Button: Fixed width prevents header shifting */}
                                    <Button 
                                        variant={activeMode === 'seller' ? 'default' : 'outline'}
                                        className={`rounded-full gap-2 transition-colors hidden sm:flex min-w-[160px] justify-center ${activeMode === 'seller' ? 'bg-blue-600 hover:bg-blue-700 text-white border-transparent' : ''}`}
                                        onClick={toggleMode}
                                        size="sm"
                                    >
                                        <RefreshCw className="w-4 h-4 shrink-0" />
                                        <span className="truncate">{activeMode === 'buyer' ? t('Switch to Selling') : t('Switch to Buying')}</span>
                                    </Button>
                                    
                                    {/* Mobile Switch Button */}
                                    <Button 
                                        variant={activeMode === 'seller' ? 'default' : 'outline'}
                                        className={`rounded-full sm:hidden h-9 px-3 gap-1.5 shrink-0 transition-colors ${
                                            activeMode === 'seller' ? 'bg-blue-600 hover:bg-blue-700 text-white border-transparent' : ''
                                        }`}
                                        onClick={toggleMode}
                                    >
                                        <RefreshCw className="w-3.5 h-3.5 shrink-0" />
                                        <span className="text-[11px] font-bold uppercase tracking-wider">
                                            {activeMode === 'buyer' ? t('Seller') : t('Buyer')}
                                        </span>
                                    </Button>

                                    <Separator orientation="vertical" className="h-6 mx-1 shrink-0 hidden sm:block" />
                                </>
                            )}
                            
                            {/* --- LANGUAGE SWITCHER --- */}
                            {availableLanguages.length > 0 && (
                                <DropdownMenu>
                                    <DropdownMenuTrigger className="hidden lg:flex items-center gap-1.5 hover:text-primary transition-colors text-sm outline-none px-2 shrink-0">
                                        <Languages className="h-[20px] w-[20px] shrink-0" strokeWidth={1.5} />
                                        <span className="font-bold uppercase">{locale}</span>
                                    </DropdownMenuTrigger>
                                    <DropdownMenuContent align="end" className="w-40 rounded-xl shadow-xl">
                                        {availableLanguages.map(lang => (
                                            <DropdownMenuItem 
                                                key={lang.code} 
                                                onClick={() => router.get(route('language.switch', lang.code))}
                                                className={`cursor-pointer ${locale === lang.code ? 'bg-primary/10 font-bold text-primary' : ''}`}
                                            >
                                                {lang.name}
                                            </DropdownMenuItem>
                                        ))}
                                    </DropdownMenuContent>
                                </DropdownMenu>
                            )}

                            {/* --- NOTIFICATIONS BELL --- */}
                            <NotificationDropdown 
                                initialUnreadCount={unreadNotificationsCount} 
                                userId={user?.id} 
                            />

                            {/* --- THEME TOGGLE --- */}
                            <ThemeToggle />
                            
                            {/* --- AVATAR (Linked to Settings) --- */}
                            <Link href={route('settings.profile')} className="shrink-0">
                                <Avatar className="w-8 h-8 border border-border cursor-pointer hover:opacity-80 shadow-sm ml-1 sm:ml-0 shrink-0">
                                    <AvatarImage src={auth?.user?.avatar_path ? `/storage/${auth.user.avatar_path}` : ''} />
                                    <AvatarFallback><User className="w-4 h-4 text-muted-foreground shrink-0" /></AvatarFallback>
                                </Avatar>
                            </Link>
                        </div>
                    </header>

                    {/* Main Content Area */}
                    <main className="p-4 md:p-8 w-full min-w-0">
                        <div className="max-w-[1400px] mx-auto w-full">
                            {children}
                        </div>
                    </main>
                </div>
            </div>
        </ThemeProvider>
    );
}