"use client";

import React, { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { BellRing, Package, MessageCircle } from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { clientFetch } from "@/lib/client-utils";
import { toast } from "sonner";
import { getCookie } from "@/lib/client-utils";
import axios from "axios";

interface Order {
  _id: string;
  orderId: string;
  status: string;
  totalPrice: number;
  orderDate: string;
}

interface ChatMessage {
  chatId: string;
  buyerId: string;
  messageCount: number;
}

interface UnreadCounts {
  totalUnread: number;
  chatCounts: Record<string, number>;
}

export default function UnifiedNotifications() {
  const router = useRouter();
  
  // Chat notification state
  const [unreadCounts, setUnreadCounts] = useState<UnreadCounts>({ totalUnread: 0, chatCounts: {} });
  const [previousUnreadTotal, setPreviousUnreadTotal] = useState<number>(0);
  const [chatMetadata, setChatMetadata] = useState<Record<string, { buyerId: string }>>({});
  
  // Order notification state
  const [newOrders, setNewOrders] = useState<Order[]>([]);
  const seenOrderIds = useRef<Set<string>>(new Set());
  const isInitialOrdersFetch = useRef(true);
  
  // Shared state
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<string>("all");
  const audioRef = useRef<HTMLAudioElement | null>(null);

  // Total notifications count
  const totalNotifications = unreadCounts.totalUnread + newOrders.length;
  
  // Initialize audio
  useEffect(() => {
    audioRef.current = new Audio('/notification.mp3');
    
    audioRef.current.addEventListener('error', () => {
      audioRef.current = null;
    });
    
    return () => {
      if (audioRef.current) {
        audioRef.current = null;
      }
    };
  }, []);
  
  // Function to play notification sound
  const playNotificationSound = () => {
    if (audioRef.current) {
      audioRef.current.currentTime = 0;
      audioRef.current.play().catch(err => {
        console.log('Error playing sound:', err);
        // Fallback beep if audio file fails
        try {
          const context = new (window.AudioContext || (window as any).webkitAudioContext)();
          const oscillator = context.createOscillator();
          oscillator.type = 'sine';
          oscillator.frequency.setValueAtTime(800, context.currentTime);
          oscillator.connect(context.destination);
          oscillator.start();
          oscillator.stop(context.currentTime + 0.2);
        } catch (e) {
          console.error('Could not play fallback audio', e);
        }
      });
    }
  };

  // Check for new paid orders
  useEffect(() => {
    // Only run this on dashboard pages
    if (typeof window === 'undefined' || !window.location.pathname.includes("/dashboard")) return;

    const checkForNewOrders = async () => {
      try {
        // Fetch orders from the last 24 hours that are in paid status
        const orderData = await clientFetch("/orders?status=paid&limit=10");
        const orders: Order[] = orderData.orders || [];

        // If this is the first fetch, just store the orders without notifications
        if (isInitialOrdersFetch.current) {
          orders.forEach(order => seenOrderIds.current.add(order._id));
          isInitialOrdersFetch.current = false;
          return;
        }

        // Check for new paid orders that haven't been seen before
        const latestNewOrders = orders.filter(order => !seenOrderIds.current.has(order._id));
        
        // Show notifications for new orders
        if (latestNewOrders.length > 0) {
          // Update the seen orders set
          latestNewOrders.forEach(order => seenOrderIds.current.add(order._id));
          
          // Show a toast notification for each new order
          latestNewOrders.forEach(order => {
            toast.success(
              <div className="flex flex-col">
                <p className="font-semibold">New Paid Order!</p>
                <p className="text-sm">Order #{order.orderId}</p>
                <p className="text-sm font-semibold">£{order.totalPrice.toFixed(2)}</p>
              </div>,
              {
                duration: 8000,
                icon: <Package className="h-5 w-5" />,
                action: {
                  label: "View",
                  onClick: () => window.open(`/dashboard/orders/${order._id}`, "_blank")
                }
              }
            );
          });
          
          // Play notification sound
          playNotificationSound();
          
          // Update the state with new orders for the dropdown
          setNewOrders(prev => [...latestNewOrders, ...prev].slice(0, 10));
        }
      } catch (error) {
        console.error("Error checking for new orders:", error);
      }
    };

    // Check for new orders every minute
    const orderInterval = setInterval(checkForNewOrders, 60000);
    
    // Initial check for orders
    checkForNewOrders();
    
    return () => {
      clearInterval(orderInterval);
    };
  }, []);

  // Fetch unread chat counts
  useEffect(() => {
    // Only run this on dashboard pages
    if (typeof window === 'undefined' || !window.location.pathname.includes("/dashboard")) return;
    
    const fetchUnreadCounts = async () => {
      try {
        const authToken = getCookie("Authorization");
        
        if (!authToken) return;
        
        const authAxios = axios.create({
          baseURL: process.env.NEXT_PUBLIC_API_URL,
          headers: {
            Authorization: `Bearer ${authToken}`
          }
        });
        
        // Get vendor info from profile endpoint
        const vendorResponse = await authAxios.get('/auth/me');
        
        // Access correct property - the vendor ID is in vendor._id
        const vendorId = vendorResponse.data.vendor?._id;
        
        if (!vendorId) {
          console.error("Vendor ID not found in profile response:", vendorResponse.data);
          return;
        }
        
        const response = await authAxios.get(`/chats/vendor/${vendorId}/unread`);
        
        // Check if there are new notifications and play sound if needed
        if (!loading && response.data.totalUnread > previousUnreadTotal) {
          playNotificationSound();
        }
        
        // Update chat state
        setUnreadCounts(response.data);
        setPreviousUnreadTotal(response.data.totalUnread);
        
        if (response.data.totalUnread > 0) {
          const chatIds = Object.keys(response.data.chatCounts);
          
          if (chatIds.length > 0) {
            // Create a simplified metadata object with just needed info
            const metadata: Record<string, { buyerId: string }> = {};
            
            // Fetch each chat to get buyer IDs
            await Promise.all(
              chatIds.map(async (chatId) => {
                try {
                  // Use markAsRead=false to ensure we don't mark messages as read
                  const chatResponse = await authAxios.get(`/chats/${chatId}?markAsRead=false`);
                  metadata[chatId] = {
                    buyerId: chatResponse.data.buyerId,
                  };
                } catch (error) {
                  console.error(`Error fetching chat ${chatId}:`, error);
                }
              })
            );
            
            setChatMetadata(metadata);
          }
        }
        
        setLoading(false);
      } catch (error) {
        console.error("Error fetching unread counts:", error);
        setLoading(false);
      }
    };
    
    // Initial fetch
    fetchUnreadCounts();
    
    // Set polling interval (every 10 seconds for more responsive chat notifications)
    const chatInterval = setInterval(fetchUnreadCounts, 10000);
    
    return () => clearInterval(chatInterval);
  }, [loading, previousUnreadTotal]);

  // Navigation handlers
  const handleChatClick = (chatId: string) => {
    router.push(`/dashboard/chats/${chatId}`);
  };
  
  const handleOrderClick = (orderId: string) => {
    router.push(`/dashboard/orders/${orderId}`);
  };
  
  // Clear notification handlers
  const clearOrderNotifications = () => {
    setNewOrders([]);
  };
  
  // Format the price as currency
  const formatPrice = (price: number) => {
    return `£${price.toFixed(2)}`;
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="ghost" size="icon" className="relative" disabled={loading}>
          <BellRing className="h-5 w-5" />
          {totalNotifications > 0 && (
            <Badge 
              variant="destructive" 
              className="absolute -top-1 -right-1 px-1.5 py-0.5 text-xs"
            >
              {totalNotifications}
            </Badge>
          )}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-80">
        <div className="p-2 border-b">
          <Tabs defaultValue="all" value={activeTab} onValueChange={setActiveTab}>
            <TabsList className="grid w-full grid-cols-3">
              <TabsTrigger value="all" className="text-xs">
                All 
                {totalNotifications > 0 && (
                  <Badge variant="secondary" className="ml-1">
                    {totalNotifications}
                  </Badge>
                )}
              </TabsTrigger>
              <TabsTrigger value="messages" className="text-xs">
                Messages
                {unreadCounts.totalUnread > 0 && (
                  <Badge variant="secondary" className="ml-1">
                    {unreadCounts.totalUnread}
                  </Badge>
                )}
              </TabsTrigger>
              <TabsTrigger value="orders" className="text-xs">
                Orders
                {newOrders.length > 0 && (
                  <Badge variant="secondary" className="ml-1">
                    {newOrders.length}
                  </Badge>
                )}
              </TabsTrigger>
            </TabsList>
          </Tabs>
        </div>
        
        <TabsContent value="all" className="m-0">
          {totalNotifications === 0 ? (
            <div className="p-4 flex items-center justify-center">
              <p className="text-sm text-muted-foreground">No new notifications</p>
            </div>
          ) : (
            <div className="max-h-96 overflow-y-auto">
              {/* Messages Section */}
              {unreadCounts.totalUnread > 0 && (
                <>
                  <div className="px-3 py-2 text-xs font-medium bg-muted/50">
                    Unread Messages
                  </div>
                  {Object.entries(unreadCounts.chatCounts).slice(0, 3).map(([chatId, count]) => (
                    <DropdownMenuItem 
                      key={`chat-${chatId}`}
                      className="p-3 cursor-pointer"
                      onClick={() => handleChatClick(chatId)}
                    >
                      <div className="flex items-center justify-between w-full">
                        <div className="flex items-center gap-2">
                          <MessageCircle className="h-4 w-4 text-blue-500" />
                          <div>
                            <p className="font-medium">
                              Customer {chatMetadata[chatId]?.buyerId.slice(-4) || 'Unknown'}
                            </p>
                            <p className="text-xs text-muted-foreground">
                              {count} new {count === 1 ? 'message' : 'messages'}
                            </p>
                          </div>
                        </div>
                        <Badge variant="secondary">{count}</Badge>
                      </div>
                    </DropdownMenuItem>
                  ))}
                  {Object.keys(unreadCounts.chatCounts).length > 3 && (
                    <div className="px-3 py-2 text-xs text-center text-muted-foreground">
                      + {Object.keys(unreadCounts.chatCounts).length - 3} more unread chats
                    </div>
                  )}
                </>
              )}
              
              {/* Divider if both types are present */}
              {unreadCounts.totalUnread > 0 && newOrders.length > 0 && (
                <DropdownMenuSeparator />
              )}
              
              {/* Orders Section */}
              {newOrders.length > 0 && (
                <>
                  <div className="px-3 py-2 text-xs font-medium bg-muted/50 flex justify-between items-center">
                    <span>New Paid Orders</span>
                    <Button 
                      variant="ghost" 
                      size="sm" 
                      onClick={(e) => {
                        e.stopPropagation();
                        clearOrderNotifications();
                      }}
                      className="h-6 text-xs"
                    >
                      Clear
                    </Button>
                  </div>
                  {newOrders.slice(0, 3).map((order) => (
                    <DropdownMenuItem 
                      key={`order-${order._id}`}
                      className="p-3 cursor-pointer"
                      onClick={() => handleOrderClick(order._id)}
                    >
                      <div className="flex items-center justify-between w-full">
                        <div className="flex items-center gap-2">
                          <Package className="h-4 w-4 text-green-500" />
                          <div>
                            <p className="font-medium">Order #{order.orderId}</p>
                            <p className="text-xs text-muted-foreground">
                              {formatPrice(order.totalPrice)}
                            </p>
                          </div>
                        </div>
                        <Badge className="bg-green-500 hover:bg-green-600">Paid</Badge>
                      </div>
                    </DropdownMenuItem>
                  ))}
                  {newOrders.length > 3 && (
                    <div className="px-3 py-2 text-xs text-center text-muted-foreground">
                      + {newOrders.length - 3} more new orders
                    </div>
                  )}
                </>
              )}
            </div>
          )}
        </TabsContent>
        
        <TabsContent value="messages" className="m-0">
          {unreadCounts.totalUnread === 0 ? (
            <div className="p-4 flex items-center justify-center">
              <p className="text-sm text-muted-foreground">No unread messages</p>
            </div>
          ) : (
            <>
              <div className="max-h-96 overflow-y-auto">
                {Object.entries(unreadCounts.chatCounts).map(([chatId, count]) => (
                  <DropdownMenuItem 
                    key={`chat-tab-${chatId}`}
                    className="p-3 cursor-pointer"
                    onClick={() => handleChatClick(chatId)}
                  >
                    <div className="flex items-center justify-between w-full">
                      <div className="flex items-center gap-2">
                        <MessageCircle className="h-4 w-4 text-blue-500" />
                        <div>
                          <p className="font-medium">
                            Customer {chatMetadata[chatId]?.buyerId.slice(-4) || 'Unknown'}
                          </p>
                          <p className="text-xs text-muted-foreground">
                            {count} new {count === 1 ? 'message' : 'messages'}
                          </p>
                        </div>
                      </div>
                      <Badge variant="secondary">{count}</Badge>
                    </div>
                  </DropdownMenuItem>
                ))}
              </div>
              <div className="p-2 border-t">
                <Button 
                  variant="outline" 
                  className="w-full"
                  onClick={() => router.push('/dashboard/chats')}
                >
                  View All Chats
                </Button>
              </div>
            </>
          )}
        </TabsContent>
        
        <TabsContent value="orders" className="m-0">
          {newOrders.length === 0 ? (
            <div className="p-4 flex items-center justify-center">
              <p className="text-sm text-muted-foreground">No new paid orders</p>
            </div>
          ) : (
            <>
              <div className="px-3 py-2 text-xs font-medium bg-muted/50 flex justify-between items-center">
                <span>New Paid Orders</span>
                <Button 
                  variant="ghost" 
                  size="sm" 
                  onClick={(e) => {
                    e.stopPropagation();
                    clearOrderNotifications();
                  }}
                  className="h-6 text-xs"
                >
                  Clear
                </Button>
              </div>
              <div className="max-h-96 overflow-y-auto">
                {newOrders.map((order) => (
                  <DropdownMenuItem 
                    key={`order-tab-${order._id}`}
                    className="p-3 cursor-pointer"
                    onClick={() => handleOrderClick(order._id)}
                  >
                    <div className="flex items-center justify-between w-full">
                      <div className="flex items-center gap-2">
                        <Package className="h-4 w-4 text-green-500" />
                        <div>
                          <p className="font-medium">Order #{order.orderId}</p>
                          <p className="text-xs text-muted-foreground">
                            {formatPrice(order.totalPrice)}
                          </p>
                        </div>
                      </div>
                      <Badge className="bg-green-500 hover:bg-green-600">Paid</Badge>
                    </div>
                  </DropdownMenuItem>
                ))}
              </div>
              <div className="p-2 border-t">
                <Button 
                  variant="outline" 
                  className="w-full"
                  onClick={() => router.push('/dashboard/orders')}
                >
                  View All Orders
                </Button>
              </div>
            </>
          )}
        </TabsContent>
      </DropdownMenuContent>
    </DropdownMenu>
  );
} 