'use client';
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuItem, } from '@/components/ui/dropdown-menu';
import { Bell } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import apis, { BUCKET_ROOT } from '@/utils/apis';
import { getValidImage } from '@/lib/utils';

interface NotificationItem {
  _id: string;
  title: string;
  description: string;
  createdAt: string;
  status: 'read' | 'unread';
  redirectPath: string;
  cart_id?: string;
}

function timeAgo(dateString: string) {
  const now = new Date();
  const then = new Date(dateString);
  const diffMs = now.getTime() - then.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  if (diffMins < 1) return 'Just now';
  if (diffMins < 60) return `${diffMins} min ago`;
  const diffHours = Math.floor(diffMins / 60);
  if (diffHours < 24) return `${diffHours} hour${diffHours > 1 ? 's' : ''} ago`;
  const diffDays = Math.floor(diffHours / 24);
  return `${diffDays} day${diffDays > 1 ? 's' : ''} ago`;
}

export default function NotificationDialog({
  open,
  setOpen,
}: {
  open: boolean;
  setOpen: (val: boolean) => void;
}) {
  const router = useRouter();
  const [notifications, setNotifications] = useState<NotificationItem[]>([]);
  const [totalUnread, setTotalUnread] = useState<number>(0); // Add state for total unread notifications
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchNotifications();
  }, []);

  const fetchNotifications = async () => {
    setLoading(true);
    try {
      const response = await apis.notificationList.listing('pageNumber=1&count=5');
      const data = response?.unread?.data || [];
      const unreadNotifications = data.map((item: any) => ({
        _id: item._id,
        title: item.notification.title,
        description: item.notification.body,
        createdAt: item.createdAt,
        status: 'unread',
        redirectPath: item.data.redirectPath,
        cart_id: item.data.cart_id,
      }));
      setNotifications(unreadNotifications.slice(0, 3)); // Keep only the first 3 notifications
      setTotalUnread(response?.unread?.total || 0); // Update the total unread notifications
    } catch (error) {
      console.error('Error fetching notifications:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <DropdownMenu open={open} onOpenChange={setOpen}>
      <DropdownMenuTrigger asChild>
        <button className="relative p-2 bg-gray-200 rounded-full shadow-lg cursor-pointer">
          <Bell strokeWidth={1.5} />
          {totalUnread > 0 && (
            <span className="absolute -top-2 -right-1 text-white flex items-center justify-center text-[8px] bg-red-600 w-5 h-5 rounded-full">
              {totalUnread}
            </span>
          )}
        </button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-80 mt-2 z-[999]">
        <DropdownMenuLabel className="font-semibold">Notifications</DropdownMenuLabel>
        <DropdownMenuSeparator />
        {loading ? (
          <DropdownMenuItem className="text-sm text-gray-500">Loading...</DropdownMenuItem>
        ) : notifications.length === 0 ? (
          <DropdownMenuItem className="text-sm text-gray-500">No Notifications.</DropdownMenuItem>
        ) : (
          notifications.map((note) => (
            <DropdownMenuItem
              key={note._id}
              className="flex flex-row justify-between items-center text-sm text-gray-700 hover:bg-gray-100 cursor-pointer py-2"
              onClick={async () => {
                try {
                  await apis.notificationList.markSingleRead(note._id);
                  setNotifications((prev) => prev.filter((n) => n._id !== note._id));
                } catch (error) {
                  console.error('Failed to mark as read', error);
                }
                // If notification has cart_id, fetch vendor-added items and redirect to grocery page
                if (note.cart_id) {
                  try {
                    const response = await apis.Grocery.getItemsForCustomer(note.cart_id);
                    if (response?.data) {
                      const cartData = response.data;
                      const restaurantId = cartData.restaurant_id?._id;
                      const otherCartItems = cartData.other_cart_items || [];

                      if (restaurantId && otherCartItems.length > 0) {
                        const cartItems = otherCartItems.map((cartItem: any) => ({
                          id: cartItem.item_id,
                          name: cartItem.name,
                          weight: `${cartItem.quantity || ''} ${cartItem.unit || ''}`.trim(),
                          price: `\u20b9${cartItem.price}.00`,
                          image: getValidImage(cartItem.imageUrl),
                          quantity: cartItem.no_of_quantity || 1,
                          restaurantId: restaurantId,
                        }));

                        localStorage.setItem('groceryCartItems', JSON.stringify(cartItems));
                        localStorage.setItem('vendorCartNotification', 'true');
                        if (cartData.restaurant_id) {
                          localStorage.setItem('restaurant_delivery_info', JSON.stringify(cartData.restaurant_id));
                        }

                        setOpen(false);
                        if (window.location.pathname === `/grocery/${restaurantId}`) {
                          window.dispatchEvent(new CustomEvent('vendor-cart-updated'));
                        } else {
                          router.push(`/grocery/${restaurantId}?type=grocery`);
                        }
                        return;
                      }
                    }
                  } catch (cartError) {
                    console.error('Error fetching vendor cart items:', cartError);
                  }
                }
                if (note.redirectPath) {
                  setOpen(false);
                  router.push(note.redirectPath);
                }
              }}
            >
              <div className="flex flex-col">
                <span className="font-medium truncate">{note.title}</span>
                <span className="text-xs text-gray-500">{timeAgo(note.createdAt)}</span>
              </div>
              {note.status === 'unread' && (
                <div className="w-2 h-2 bg-brand-500 rounded-full ml-2" />
              )}
            </DropdownMenuItem>
          ))
        )}
        {notifications.length > 2 && (
          <>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              className="text-center justify-center text-sm text-neutral-900 font-semibold hover:bg-gray-100 cursor-pointer"
              onClick={() => {
                setOpen(false);
                router.push('/notification');
              }}
            >
              View All
            </DropdownMenuItem>
          </>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
