import React, { useState, useRef, useEffect } from 'react';
import { Link, usePage, router } from '@inertiajs/react';
import axios from 'axios'; // <-- NEW: Added axios for polling
import { ThemeProvider, useTheme } from "@/Components/ThemeProvider";
import { Button } from "@/Components/ui/button";
import { 
    Globe, MessageSquareText, ClipboardList, ShoppingCart, 
    Sun, Moon, Search as SearchIcon, ChevronLeft, ChevronRight, 
    LayoutGrid, X, Languages 
} from "lucide-react";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/Components/ui/dropdown-menu";
import ProfileMenu from './ProfileMenu';
import LiveSearch from '../LiveSearch';
import CategoryModal from '@/Components/CategoryModal';
import Logo from '@/Components/Logo'; 
import { useTranslation } from '@/hooks/useTranslation'; 

function ThemeToggle() {
    const { theme, setTheme } = useTheme();
    return (
        <button 
            onClick={() => setTheme(theme === "light" ? "dark" : "light")} 
            className="flex items-center gap-1 hover:text-primary transition-colors outline-none px-1 sm:px-2"
        >
            {theme === "light" ? (
                <Moon className="h-[22px] w-[22px] sm:h-[20px] sm:w-[20px]" strokeWidth={1.5} />
            ) : (
                <Sun className="h-[22px] w-[22px] sm:h-[20px] sm:w-[20px]" strokeWidth={1.5} />
            )}
        </button>
    );
}

export default function Header() {
    const { auth, appSettings, cartCount, unreadMessagesCount, activeCurrency, currencies, globalCategories = [], availableLanguages = [], locale } = usePage().props;
    const { t } = useTranslation(); 

    // --- State for Real-Time / Polling Unread Count ---
    const [localUnreadCount, setLocalUnreadCount] = useState(unreadMessagesCount || 0);

    const [isCategoryModalOpen, setIsCategoryModalOpen] = useState(false);
    const [selectedCategoryId, setSelectedCategoryId] = useState(null);
    const scrollRef = useRef(null);
    const [showLeftArrow, setShowLeftArrow] = useState(false);
    const [showRightArrow, setShowRightArrow] = useState(true);
    const [isMobileSearchOpen, setIsMobileSearchOpen] = useState(false);

    // 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) {
                // Silently fail to avoid console spam during downtime
            }
        };

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

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

        // If Laravel Echo/Reverb is configured
        if (window.Echo && window.Echo.connector.pusher) {
            const connection = window.Echo.connector.pusher.connection;
            
            // Listen on the user's global channel for instant updates
            window.Echo.private(`user.${auth.user.id}`)
                .listen('MessageSent', () => {
                    fetchUnreadCount(); // Refresh count when a new message arrives
                });

            // Detect WebSocket states and fallback automatically
            connection.bind('state_change', (states) => {
                if (states.current === 'unavailable' || states.current === 'disconnected') {
                    startPolling(); // Fallback to 10s API polling
                } else if (states.current === 'connected') {
                    stopPolling(); // Stop polling if WS is working perfectly
                }
            });

            connection.bind('error', () => {
                startPolling(); // Fallback on WS error
            });
            
            // If already disconnected on load
            if (connection.state !== 'connected') {
                startPolling();
            }
        } else {
            // Echo is completely missing, start 10s polling immediately
            startPolling();
        }

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

    // Search and routing cleanup
    useEffect(() => {
        const unsubscribe = router.on('navigate', () => {
            setIsMobileSearchOpen(false);
        });
        return () => unsubscribe();
    }, []);

    const checkScroll = () => {
        if (scrollRef.current) {
            const { scrollLeft, scrollWidth, clientWidth } = scrollRef.current;
            setShowLeftArrow(scrollLeft > 0);
            setShowRightArrow(Math.ceil(scrollLeft + clientWidth) < scrollWidth - 5);
        }
    };

    useEffect(() => {
        if (!isMobileSearchOpen) {
            checkScroll();
            window.addEventListener('resize', checkScroll);
            return () => window.removeEventListener('resize', checkScroll);
        }
    }, [globalCategories, isMobileSearchOpen]);

    const scroll = (direction) => {
        if (scrollRef.current) {
            const offset = direction === 'left' ? -150 : 150;
            scrollRef.current.scrollBy({ left: offset, behavior: 'smooth' });
            setTimeout(checkScroll, 300);
        }
    };

    const openCategoryModal = (categoryId = null) => {
        setSelectedCategoryId(categoryId);
        setIsCategoryModalOpen(true);
    };

    return (
        <>
            <CategoryModal 
                isOpen={isCategoryModalOpen} 
                onClose={() => setIsCategoryModalOpen(false)} 
                categories={globalCategories}
                initialCategoryId={selectedCategoryId}
            />

            <nav className="sticky top-0 z-50 w-full bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/60 shadow-sm border-b">
                <div className="flex h-[72px] items-center justify-between px-4 lg:px-8 max-w-[1600px] mx-auto gap-4 lg:gap-12">
                    
                    <Link href={route('home')} className="flex items-center hover:opacity-80 transition-opacity shrink-0 outline-none">
                        <Logo className="w-[100px] h-[50px] sm:w-[130px] sm:h-[65px]" />
                    </Link>
                    
                    <LiveSearch 
                        containerClassName="hidden md:flex max-w-3xl"
                        inputClassName="rounded-full border-2 border-primary/40 bg-background px-6 py-2.5 text-[15px] focus:border-primary focus:ring-1 focus:ring-primary pr-28"
                        buttonClassName="rounded-l-none rounded-r-full bg-primary hover:bg-primary/90 text-primary-foreground px-8 text-[15px] font-bold"
                        placeholder={t('Search products, categories...')} 
                        buttonText={t('Search')} 
                    />

                    <div className="flex items-center gap-3 sm:gap-5 ml-auto text-muted-foreground shrink-0">
                        
                        {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">
                                    <Languages className="h-[20px] w-[20px]" 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>
                        )}

                        <DropdownMenu>
                            <DropdownMenuTrigger className="hidden lg:flex items-center gap-1.5 hover:text-primary transition-colors text-sm outline-none px-2">
                                <Globe className="h-[20px] w-[20px]" strokeWidth={1.5} />
                                <span className="font-bold">{activeCurrency?.code || 'USD'}</span>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end" className="w-40 rounded-xl shadow-xl">
                                {currencies?.map(c => (
                                    <DropdownMenuItem 
                                        key={c.code} 
                                        onClick={() => router.get(route('currency.switch', c.code))}
                                        className={`cursor-pointer ${activeCurrency?.code === c.code ? 'bg-primary/10 font-bold text-primary' : ''}`}
                                    >
                                        {c.code} ({c.symbol})
                                    </DropdownMenuItem>
                                ))}
                            </DropdownMenuContent>
                        </DropdownMenu>

                        <ThemeToggle />

                        <button 
                            onClick={() => setIsMobileSearchOpen(!isMobileSearchOpen)} 
                            className="md:hidden hover:text-primary transition-colors px-1 outline-none"
                        >
                            <SearchIcon className="h-[22px] w-[22px]" strokeWidth={1.5} />
                        </button>

                        {/* LIVE UPDATING MESSAGE ICON */}
                        <Link href={route('chat.index')} className="relative hover:text-primary transition-colors px-1">
                            <MessageSquareText className="h-[22px] w-[22px]" strokeWidth={1.5} />
                            {localUnreadCount > 0 && (
                                <span className="absolute -top-1.5 -right-1.5 bg-blue-500 text-white text-[10px] w-4 h-4 flex items-center justify-center rounded-full font-bold shadow-sm">
                                    {localUnreadCount > 99 ? '99+' : localUnreadCount}
                                </span>
                            )}
                        </Link>
                        
                        <Link href={route('buyer.orders.index')} className="hover:text-primary transition-colors px-1 hidden sm:block">
                            <ClipboardList className="h-[22px] w-[22px]" strokeWidth={1.5} />
                        </Link>
                        
                        <Link href={route('marketplace.cart.index')} className="relative hover:text-primary transition-colors px-1">
                            <ShoppingCart className="h-[22px] w-[22px]" strokeWidth={1.5} />
                            {cartCount > 0 && (
                                <span className="absolute -top-1.5 -right-1.5 bg-red-500 text-white text-[10px] w-4 h-4 flex items-center justify-center rounded-full font-bold shadow-sm">
                                    {cartCount > 99 ? '99+' : cartCount}
                                </span>
                            )}
                        </Link>
                        
                        <ProfileMenu />
                    </div>
                </div>
                
                <div className="md:hidden w-full bg-background border-t border-border/50">
                    {isMobileSearchOpen ? (
                        <div className="flex items-center gap-2 px-4 py-2.5 animate-in fade-in slide-in-from-top-1">
                            <LiveSearch 
                                showButton={false}
                                placeholder={t('Search products...')} 
                                containerClassName="w-full"
                                inputClassName="rounded-full border bg-muted/50 pl-10 pr-4 py-2.5 text-sm focus:border-primary focus:bg-background transition-all shadow-inner"
                            />
                            <button 
                                onClick={() => setIsMobileSearchOpen(false)}
                                className="p-2 bg-muted/50 hover:bg-muted text-muted-foreground hover:text-foreground rounded-full outline-none shrink-0 transition-colors"
                            >
                                <X className="w-5 h-5" />
                            </button>
                        </div>
                    ) : (
                        <div className="relative w-full animate-in fade-in slide-in-from-bottom-1">
                            {showLeftArrow && (
                                <button 
                                    onClick={() => scroll('left')}
                                    className="absolute left-0 top-0 bottom-0 z-10 w-10 bg-gradient-to-r from-background to-transparent flex items-center justify-start pl-2 text-primary"
                                >
                                    <ChevronLeft className="w-5 h-5" />
                                </button>
                            )}

                            <div 
                                ref={scrollRef}
                                onScroll={checkScroll}
                                className="flex overflow-x-auto no-scrollbar px-3 py-2.5 snap-x scroll-smooth"
                            >
                                <div className="flex w-max gap-3">
                                    {globalCategories?.map((cat) => (
                                        <button
                                            key={cat.id}
                                            onClick={() => openCategoryModal(cat.id)}
                                            className="flex items-center gap-2 px-3 py-1.5 rounded-full bg-muted/40 hover:bg-muted border border-border/60 whitespace-nowrap snap-center shrink-0 transition-colors"
                                        >
                                            {cat.image_path ? (
                                                <img src={`/storage/${cat.image_path}`} className="w-4 h-4 object-contain grayscale" alt="" />
                                            ) : (
                                                <LayoutGrid className="w-4 h-4 text-muted-foreground" />
                                            )}
                                            <span className="text-xs font-bold text-foreground/80">{cat.name}</span>
                                        </button>
                                    ))}
                                </div>
                            </div>

                            {showRightArrow && (
                                <button 
                                    onClick={() => scroll('right')}
                                    className="absolute right-0 top-0 bottom-0 z-10 w-10 bg-gradient-to-l from-background to-transparent flex items-center justify-end pr-2 text-primary"
                                >
                                    <ChevronRight className="w-5 h-5" />
                                </button>
                            )}
                        </div>
                    )}
                </div>
            </nav>
        </>
    );
}