// components/layout/NotificationBell.tsx
"use client";

import React, { useState, useEffect } from "react";
import { Bell } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/components/ui/popover";
import { useRouter } from "next/navigation";
import { format } from "date-fns";

interface Notification {
    user: {
        id: string;
        firstName: string;
        lastName: string;
        username: string;
    };
    unreadCount: number;
    latestMessage: {
        id: string;
        content: string;
        createdAt: string;
        conversation: {
            id: string;
        };
    };
}

export function NotificationBell() {
    const [notifications, setNotifications] = useState<Notification[]>([]);
    const [isLoading, setIsLoading] = useState(false);
    const router = useRouter();

    const fetchNotifications = async () => {
        setIsLoading(true);
        try {
            const res = await fetch("/api/notifications");
            if (res.ok) {
                const data = await res.json();
                setNotifications(data);
            }
        } catch (error) {
            console.error("Error fetching notifications:", error);
        } finally {
            setIsLoading(false);
        }
    };

    useEffect(() => {
        fetchNotifications();

        // Set up an interval to fetch notifications every 30 seconds
        const intervalId = setInterval(() => {
            fetchNotifications();
        }, 30000);

        return () => clearInterval(intervalId);
    }, []);

    const totalUnread = notifications.reduce((sum, notification) => sum + notification.unreadCount, 0);

    const handleNotificationClick = async (userId: string, conversationId: string) => {
        try {
            // Mark the messages as read
            await fetch(`/api/users/${userId}/conversations/${conversationId}/read`, {
                method: "POST",
            });

            // Navigate to the user's conversation page
            router.push(`/dashboard/users/${userId}`);

            // Remove this notification from the list
            setNotifications(notifications.filter(n =>
                !(n.user.id === userId && n.latestMessage.conversation.id === conversationId)
            ));
        } catch (error) {
            console.error("Error marking messages as read:", error);
        }
    };

    return (
        <Popover>
            <PopoverTrigger asChild>
                <div className="relative cursor-pointer">
                    <Bell className="h-5 w-5" />
                    {totalUnread > 0 && (
                        <Badge className="absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 rounded-full">
                            {totalUnread}
                        </Badge>
                    )}
                </div>
            </PopoverTrigger>
            <PopoverContent className="w-80" align="end" dir="rtl">
                <div className="space-y-4">
                    <h4 className="font-medium text-sm">پیام‌های خوانده نشده</h4>

                    {isLoading ? (
                        <div className="text-center py-4">
                            <span className="text-muted-foreground">در حال بارگذاری...</span>
                        </div>
                    ) : notifications.length === 0 ? (
                        <div className="text-center py-4">
                            <span className="text-muted-foreground">پیام خوانده‌نشده‌ای وجود ندارد</span>
                        </div>
                    ) : (
                        <div className="space-y-3 max-h-[300px] overflow-y-auto">
                            {notifications.map((notification) => (
                                <div
                                    key={`${notification.user.id}-${notification.latestMessage.id}`}
                                    className="bg-muted/50 rounded-lg p-3 cursor-pointer hover:bg-muted"
                                    onClick={() => handleNotificationClick(
                                        notification.user.id,
                                        notification.latestMessage.conversation.id
                                    )}
                                >
                                    <div className="flex justify-between items-start">
                                        <div>
                                            <p className="font-medium">
                                                {notification.user.firstName} {notification.user.lastName}
                                            </p>
                                            <p className="text-xs text-muted-foreground">
                                                {notification.user.username ? `@${notification.user.username}` : "بدون نام کاربری"}
                                            </p>
                                        </div>
                                        <Badge>{notification.unreadCount} پیام</Badge>
                                    </div>
                                    <p className="text-sm mt-2 line-clamp-2">
                                        {notification.latestMessage.content}
                                    </p>
                                    <p className="text-xs text-muted-foreground mt-1 text-left">
                                        {format(new Date(notification.latestMessage.createdAt), "HH:mm - yyyy/MM/dd")}
                                    </p>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </PopoverContent>
        </Popover>
    );
}