import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { router } from '@inertiajs/react';
import { Popover, PopoverContent, PopoverTrigger } from "@/Components/ui/popover";
import { Bell, Check, Package, AlertTriangle, CheckCircle2, Truck, Loader2, Trash2, ArrowDownCircle } from 'lucide-react';
import { useTranslation } from '@/hooks/useTranslation';

export default function NotificationDropdown({ initialUnreadCount, userId }) {
    const { t } = useTranslation();
    const [open, setOpen] = useState(false);
    const [notifications, setNotifications] = useState([]);
    const [loading, setLoading] = useState(false);
    const [loadingMore, setLoadingMore] = useState(false);
    const [nextPageUrl, setNextPageUrl] = useState(null);
    const [unreadCount, setUnreadCount] = useState(initialUnreadCount || 0);

    useEffect(() => {
        setUnreadCount(initialUnreadCount || 0);
    }, [initialUnreadCount]);

    useEffect(() => {
        if (!userId) return;

        let pollInterval;
        const channelName = `App.Models.User.${userId}`;

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

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

        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(channelName)
                .notification((notification) => {
                    const normalizedNotification = {
                        id: notification.id || Date.now().toString(),
                        data: notification.data || notification, 
                        created_at: notification.created_at || new Date().toISOString(),
                        read_at: null,
                    };

                    setNotifications(prev => [normalizedNotification, ...prev]);
                    setUnreadCount(prev => prev + 1);
                });

            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(channelName);
            }
        };
    }, [userId]);

    const fetchNotifications = async () => {
        setLoading(true);
        try {
            const res = await axios.get(route('notifications.index'));
            setNotifications(res.data.data); 
            setNextPageUrl(res.data.next_page_url);
            
            const actualUnread = res.data.data.filter(n => n.read_at === null).length;
            if (res.data.current_page === 1) {
                setUnreadCount(actualUnread);
            }
        } catch (e) {
            console.error("Failed to fetch notifications", e);
        } finally {
            setLoading(false);
        }
    };

    const handleLoadMore = async () => {
        if (!nextPageUrl) return;
        setLoadingMore(true);
        try {
            const res = await axios.get(nextPageUrl);
            setNotifications(prev => {
                const newNotifs = res.data.data.filter(n => !prev.some(p => p.id === n.id));
                return [...prev, ...newNotifs];
            });
            setNextPageUrl(res.data.next_page_url);
        } catch (e) {
            console.error("Failed to load more", e);
        } finally {
            setLoadingMore(false);
        }
    };

    const handleOpen = (isOpen) => {
        setOpen(isOpen);
        if (isOpen && notifications.length === 0) {
            fetchNotifications();
        }
    };

    const markAsRead = async (id, url) => {
        try {
            setNotifications(prev => prev.map(n => n.id === id ? { ...n, read_at: new Date() } : n));
            setUnreadCount(prev => Math.max(0, prev - 1));
            
            await axios.post(route('notifications.read', id));
            
            if (url) {
                setOpen(false);
                router.get(url);
            }
        } catch (e) {
            console.error(e);
        }
    };

    const markAllAsRead = async () => {
        try {
            setNotifications(prev => prev.map(n => ({ ...n, read_at: new Date() })));
            setUnreadCount(0);
            await axios.post(route('notifications.read-all'));
        } catch (e) {
            console.error(e);
        }
    };

    const clearAll = async () => {
        try {
            setNotifications([]);
            setUnreadCount(0);
            setNextPageUrl(null);
            // --- FIX: Form Method Spoofing to bypass ModSecurity Firewall ---
            await axios.post(route('notifications.clear-all'), { _method: 'DELETE' });
        } catch (e) {
            console.error(e);
        }
    };

    const getIcon = (type) => {
        switch(type) {
            case 'order': return <Package className="w-4 h-4 text-blue-500" />;
            case 'success': return <CheckCircle2 className="w-4 h-4 text-green-500" />;
            case 'truck': return <Truck className="w-4 h-4 text-amber-500" />;
            case 'alert': return <AlertTriangle className="w-4 h-4 text-red-500" />;
            default: return <Bell className="w-4 h-4 text-orange-500" />;
        }
    };

    return (
        <Popover open={open} onOpenChange={handleOpen}>
            
            <PopoverTrigger className="relative flex items-center justify-center h-9 w-9 shrink-0 rounded-full hover:bg-muted outline-none transition-colors border-0 bg-transparent cursor-pointer">
                <Bell className="w-5 h-5 text-foreground" />
                {unreadCount > 0 && (
                    <span className="absolute top-0 right-0 bg-red-500 text-white text-[9px] w-4 h-4 flex items-center justify-center rounded-full font-bold shadow-sm">
                        {unreadCount > 99 ? '99+' : unreadCount}
                    </span>
                )}
            </PopoverTrigger>

            <PopoverContent align="end" className="w-80 sm:w-96 p-0 shadow-2xl rounded-xl border-border/50 z-[9999] flex flex-col max-h-[85vh]">
                
                <div className="flex items-center justify-between p-4 border-b bg-muted/10 shrink-0">
                    <h4 className="font-bold text-sm">{t('Notifications')}</h4>
                    <div className="flex items-center gap-3">
                        {unreadCount > 0 && (
                            <button onClick={markAllAsRead} className="text-[10px] font-bold text-primary hover:underline flex items-center gap-1 uppercase tracking-wider transition-colors">
                                <Check className="w-3 h-3" /> {t('Read')}
                            </button>
                        )}
                        {notifications.length > 0 && (
                            <button onClick={clearAll} className="text-[10px] font-bold text-destructive hover:underline flex items-center gap-1 uppercase tracking-wider transition-colors">
                                <Trash2 className="w-3 h-3" /> {t('Clear')}
                            </button>
                        )}
                    </div>
                </div>

                <div className="flex-1 overflow-y-auto custom-scrollbar">
                    {loading ? (
                        <div className="p-8 flex justify-center">
                            <Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
                        </div>
                    ) : notifications.length === 0 ? (
                        <div className="p-8 text-center text-muted-foreground text-sm flex flex-col items-center">
                            <Bell className="w-8 h-8 opacity-20 mb-2" />
                            {t("You're all caught up!")}
                        </div>
                    ) : (
                        <div className="divide-y divide-border/50">
                            {notifications.map((notif) => {
                                const data = notif.data || {};
                                const isUnread = !notif.read_at;

                                return (
                                    <div 
                                        key={notif.id} 
                                        onClick={() => markAsRead(notif.id, data.action_url)}
                                        className={`p-4 flex gap-3 transition-colors cursor-pointer hover:bg-muted/50 ${isUnread ? 'bg-primary/5' : 'bg-background'}`}
                                    >
                                        <div className={`p-2 border rounded-full shrink-0 h-fit shadow-sm ${isUnread ? 'bg-background' : 'bg-muted/30'}`}>
                                            {getIcon(data.icon_type)}
                                        </div>
                                        <div className="flex-1 min-w-0">
                                            <p className={`text-sm ${isUnread ? 'font-bold text-foreground' : 'font-medium text-foreground/80'}`}>
                                                {t(data.title || 'Notification')}
                                            </p>
                                            <p className={`text-xs mt-0.5 line-clamp-2 ${isUnread ? 'text-foreground/90' : 'text-muted-foreground'}`}>
                                                {t(data.message || '')}
                                            </p>
                                            <p className="text-[10px] text-muted-foreground mt-1.5 font-medium">
                                                {new Date(notif.created_at).toLocaleString()}
                                            </p>
                                        </div>
                                        {isUnread && <div className="w-2 h-2 bg-primary rounded-full mt-2 shrink-0 shadow-sm" />}
                                    </div>
                                );
                            })}

                            {nextPageUrl && (
                                <div className="p-4 text-center">
                                    <button 
                                        onClick={handleLoadMore}
                                        disabled={loadingMore}
                                        className="text-xs font-bold text-primary hover:underline flex items-center justify-center gap-1.5 mx-auto transition-colors disabled:opacity-50"
                                    >
                                        {loadingMore ? <Loader2 className="w-4 h-4 animate-spin" /> : <ArrowDownCircle className="w-4 h-4" />}
                                        {loadingMore ? t('Loading...') : t('Load Older Notifications')}
                                    </button>
                                </div>
                            )}
                        </div>
                    )}
                </div>
            </PopoverContent>
        </Popover>
    );
}