"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 { Bell } from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { clientFetch } from "@/lib/client-utils";

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

export default function ChatNotifications() {
  const router = useRouter();
  const [unreadCounts, setUnreadCounts] = useState<UnreadCounts>({ totalUnread: 0, chatCounts: {} });
  const [previousUnreadTotal, setPreviousUnreadTotal] = useState<number>(0);
  const [loading, setLoading] = useState(true);
  const [chatMetadata, setChatMetadata] = useState<Record<string, { buyerId: string }>>({});
  const audioRef = useRef<HTMLAudioElement | null>(null);
  
  useEffect(() => {
    audioRef.current = new Audio('/notification.mp3');
    
    // Fallback if notification.mp3 doesn't exist - use browser API for a simple beep
    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 to simple 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);
        }
      });
    } else {
      // Fallback to simple beep if audio element is not available
      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);
      }
    }
  };

  // Fetch unread counts
  useEffect(() => {
    const fetchUnreadCounts = async () => {
      try {
        // Use clientFetch instead of direct API calls to leverage the Next.js API rewrite rules
        
        // Get vendor info from profile endpoint
        const vendorData = await clientFetch('/auth/me');
        
        // Access correct property - the vendor ID is in vendor._id
        const vendorId = vendorData.vendor?._id;
        
        if (!vendorId) {
          console.error("Vendor ID not found in profile response:", vendorData);
          return;
        }
        
        const response = await clientFetch(`/chats/vendor/${vendorId}/unread`);
        
        // Check if there are new notifications and play sound if needed
        if (!loading && response.totalUnread > previousUnreadTotal) {
          playNotificationSound();
        }
        
        // Update state - clientFetch already parses the JSON
        setUnreadCounts(response);
        setPreviousUnreadTotal(response.totalUnread);
        
        if (response.totalUnread > 0) {
          const chatIds = Object.keys(response.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 clientFetch(`/chats/${chatId}?markAsRead=false`);
                  metadata[chatId] = {
                    buyerId: chatResponse.buyerId,
                  };
                } catch (error) {
                  console.error(`Error fetching chat ${chatId}:`, error);
                }
              })
            );
            
            setChatMetadata(metadata);
          }
        }
      } catch (error) {
        console.error("Error fetching unread counts:", error);
      } finally {
        setLoading(false);
      }
    };
    
    fetchUnreadCounts();
    
    // Set polling interval (every 10 seconds for more responsive notifications)
    const intervalId = setInterval(fetchUnreadCounts, 10000);
    
    return () => clearInterval(intervalId);
  }, [loading, previousUnreadTotal]);
  
  const handleChatClick = (chatId: string) => {
    router.push(`/dashboard/chats/${chatId}`);
  };
  
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="ghost" size="icon" className="relative" disabled={loading}>
          <Bell className="h-5 w-5" />
          {unreadCounts.totalUnread > 0 && (
            <Badge 
              variant="destructive" 
              className="absolute -top-1 -right-1 px-1.5 py-0.5 text-xs"
            >
              {unreadCounts.totalUnread}
            </Badge>
          )}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-72">
        <div className="p-2 border-b">
          <h3 className="font-medium">Messages</h3>
        </div>
        
        {unreadCounts.totalUnread === 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-80 overflow-y-auto">
              {Object.entries(unreadCounts.chatCounts).map(([chatId, count]) => (
                <DropdownMenuItem 
                  key={chatId} 
                  className="p-3 cursor-pointer"
                  onClick={() => handleChatClick(chatId)}
                >
                  <div className="flex items-center justify-between w-full">
                    <div>
                      <p className="font-medium">
                        Customer {chatMetadata[chatId]?.buyerId.slice(-4) || 'Unknown'}
                      </p>
                      <p className="text-sm text-muted-foreground">
                        {count} new {count === 1 ? 'message' : 'messages'}
                      </p>
                    </div>
                    <Badge variant="destructive">{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>
          </>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
} 