"use client"

import React, { useState, useEffect } 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 axios from "axios";
import { getCookie } 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 [loading, setLoading] = useState(true);
  const [chatMetadata, setChatMetadata] = useState<Record<string, { buyerId: string }>>({});
  
  // Fetch unread counts
  useEffect(() => {
    const fetchUnreadCounts = async () => {
      try {
        const vendorId = getCookie("vendorId");
        
        if (!vendorId) return;
        
        const response = await axios.get(`/api/chats/vendor/${vendorId}/unread`);
        setUnreadCounts(response.data);
        
        // If there are unread messages, fetch chat metadata
        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 {
                  const chatResponse = await axios.get(`/api/chats/${chatId}`);
                  metadata[chatId] = {
                    buyerId: chatResponse.data.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 30 seconds)
    const intervalId = setInterval(fetchUnreadCounts, 30000);
    
    return () => clearInterval(intervalId);
  }, []);
  
  const handleChatClick = (chatId: string) => {
    router.push(`/dashboard/chats/${chatId}`);
  };
  
  if (loading || unreadCounts.totalUnread === 0) {
    return (
      <Button variant="ghost" size="icon" className="relative" disabled={loading}>
        <Bell className="h-5 w-5" />
      </Button>
    );
  }
  
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="ghost" size="icon" className="relative">
          <Bell className="h-5 w-5" />
          <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">Unread Messages</h3>
        </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>
  );
} 