"use client"

import React, { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { formatDistanceToNow } from "date-fns";
import axios from "axios";
import { toast } from "sonner";
import { getCookie } from "@/lib/client-utils";

interface Chat {
  _id: string;
  buyerId: string;
  vendorId: string;
  storeId: string;
  lastUpdated: string;
  orderId?: string;
}

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

export default function ChatList() {
  const router = useRouter();
  const [chats, setChats] = useState<Chat[]>([]);
  const [loading, setLoading] = useState(true);
  const [unreadCounts, setUnreadCounts] = useState<UnreadCounts>({ totalUnread: 0, chatCounts: {} });
  const [previousTotalUnread, setPreviousTotalUnread] = useState<number>(0);
  const [selectedStore, setSelectedStore] = useState<string>("");
  const [vendorStores, setVendorStores] = useState<{ _id: string, name: string }[]>([]);
  const audioRef = useRef<HTMLAudioElement | null>(null);
  
  // Initialize audio element
  useEffect(() => {
    // Create audio element for notification sound
    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 vendor ID and stores
  useEffect(() => {
    const fetchVendorData = async () => {
      try {
        // Get auth token from cookies
        const authToken = getCookie("Authorization");
        
        if (!authToken) {
          toast.error("You need to be logged in to view chats");
          router.push("/auth/login");
          return;
        }
        
        // Set up axios with the auth token
        const authAxios = axios.create({
          baseURL: process.env.NEXT_PUBLIC_API_URL,
          headers: {
            Authorization: `Bearer ${authToken}`
          }
        });

        // First, get vendor info using the /auth/me endpoint
        const vendorResponse = await authAxios.get('/auth/me');
        console.log("Vendor auth response:", vendorResponse.data);
        
        // 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);
          toast.error("Could not retrieve vendor information");
          return;
        }
        
        // Fetch vendor's store using storefront endpoint
        const storeResponse = await authAxios.get(`/storefront`);
        console.log("Store response:", storeResponse.data);
        
        // Handle both array and single object responses
        if (Array.isArray(storeResponse.data)) {
          // If it's an array, use it as is
          setVendorStores(storeResponse.data);
          
          if (storeResponse.data.length > 0) {
            setSelectedStore(storeResponse.data[0]._id);
          }
        } else if (storeResponse.data && typeof storeResponse.data === 'object' && storeResponse.data._id) {
          // If it's a single store object, convert it to an array with one element
          const singleStore = [storeResponse.data];
          setVendorStores(singleStore);
          setSelectedStore(storeResponse.data._id);
        } else {
          console.error("Expected store data but received:", storeResponse.data);
          setVendorStores([]);
          toast.error("Failed to load store data in expected format");
        }
      } catch (error) {
        console.error("Error fetching vendor data:", error);
        toast.error("Failed to load vendor data");
        setVendorStores([]);
      }
    };
    
    fetchVendorData();
  }, [router]);
  
  // Fetch chats and unread counts when store is selected
  useEffect(() => {
    const fetchChats = async () => {
      if (!selectedStore) {
        console.log("No store selected, skipping fetch chats");
        setLoading(false);
        return;
      }
      
      console.log("Fetching chats for store:", selectedStore);
      setLoading(true);
      try {
        // Get auth token from cookies
        const authToken = getCookie("Authorization");
        
        if (!authToken) {
          console.log("No auth token found");
          toast.error("You need to be logged in");
          router.push("/auth/login");
          setLoading(false);
          return;
        }
        
        // Set up axios with the auth token
        const authAxios = axios.create({
          baseURL: process.env.NEXT_PUBLIC_API_URL,
          headers: {
            Authorization: `Bearer ${authToken}`
          }
        });
        
        // Get vendor ID from profile
        const vendorResponse = await authAxios.get('/auth/me');
        console.log("Vendor response:", vendorResponse.data);
        
        // 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);
          toast.error("Could not retrieve vendor information");
          setLoading(false);
          return;
        }
        
        // Fetch chats
        console.log("Fetching chats for vendor:", vendorId);
        const chatsResponse = await authAxios.get(`/chats/vendor/${vendorId}`);
        console.log("Chats response:", chatsResponse.data);
        
        // Filter chats by selected store
        const filteredChats = chatsResponse.data.filter(
          (chat: Chat) => chat.storeId === selectedStore
        );
        console.log("Filtered chats:", filteredChats);
        
        setChats(filteredChats);
        
        // Fetch unread counts
        const unreadResponse = await authAxios.get(`/chats/vendor/${vendorId}/unread`);
        console.log("Unread counts:", unreadResponse.data);
        
        // Check if there are new unread messages and play sound
        if (!loading && unreadResponse.data.totalUnread > previousTotalUnread) {
          playNotificationSound();
        }
        
        // Update states
        setUnreadCounts(unreadResponse.data);
        setPreviousTotalUnread(unreadResponse.data.totalUnread);
        setLoading(false);
        
        console.log("Chat loading complete");
      } catch (error) {
        console.error("Error fetching chats:", error);
        toast.error("Failed to load chats");
      } finally {
        console.log("Loading state set to false");
      }
    };
    
    fetchChats();
    
    // Set up polling for updates every 30 seconds
    const intervalId = setInterval(fetchChats, 10000);
    
    return () => clearInterval(intervalId);
  }, [selectedStore]);
  
  // Handle chat selection
  const handleChatClick = (chatId: string) => {
    router.push(`/dashboard/chats/${chatId}`);
  };
  
  // Handle store change
  const handleStoreChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setSelectedStore(e.target.value);
  };
  
  // Create a new chat
  const handleCreateChat = () => {
    router.push("/dashboard/chats/new");
  };
  
  if (loading) {
    return (
      <Card className="w-full">
        <CardHeader>
          <CardTitle className="flex justify-between items-center">
            <span>Loading chats...</span>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="animate-pulse space-y-4">
            {[1, 2, 3].map((n) => (
              <div key={n} className="h-16 bg-muted rounded-md"></div>
            ))}
          </div>
        </CardContent>
      </Card>
    );
  }
  
  return (
    <Card className="w-full">
      <CardHeader>
        <CardTitle className="flex justify-between items-center">
          <span>Customer Chats</span>
          <Button onClick={handleCreateChat}>New Chat</Button>
        </CardTitle>
        {vendorStores.length === 0 ? (
          <div className="text-sm text-muted-foreground">
            No store available. Please create a store first.
          </div>
        ) : vendorStores.length === 1 ? (
          <div className="text-sm font-medium">
            {vendorStores[0].name}
          </div>
        ) : (
          <div className="flex items-center space-x-2">
            <label htmlFor="store-select" className="text-sm font-medium">
              Store:
            </label>
            <select
              id="store-select"
              value={selectedStore}
              onChange={handleStoreChange}
              className="rounded-md border border-input bg-background px-3 py-2 text-sm"
            >
              {vendorStores.map((store) => (
                <option key={store._id} value={store._id}>
                  {store.name}
                </option>
              ))}
            </select>
          </div>
        )}
      </CardHeader>
      <CardContent>
        {chats.length === 0 ? (
          <div className="text-center py-12 px-4">
            <div className="mb-4 mx-auto w-16 h-16 rounded-full bg-muted flex items-center justify-center">
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-muted-foreground">
                <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
              </svg>
            </div>
            <h3 className="text-lg font-medium">No chats available</h3>
            <p className="text-muted-foreground mt-2 mb-4">
              There are no customer conversations for this store yet.
            </p>
            <Button
              variant="default"
              onClick={handleCreateChat}
              className="mt-2"
            >
              Start a new conversation
            </Button>
          </div>
        ) : (
          <div className="space-y-4">
            {chats.map((chat) => (
              <div
                key={chat._id}
                className="flex items-center justify-between p-4 rounded-lg border cursor-pointer hover:bg-muted/50 transition-colors"
                onClick={() => handleChatClick(chat._id)}
              >
                <div className="flex items-center space-x-4">
                  <Avatar>
                    <AvatarFallback>
                      {chat.buyerId.slice(0, 2).toUpperCase()}
                    </AvatarFallback>
                  </Avatar>
                  <div>
                    <h4 className="font-medium">Customer {chat.buyerId.slice(-4)}</h4>
                    <p className="text-sm text-muted-foreground">
                      {formatDistanceToNow(new Date(chat.lastUpdated), { addSuffix: true })}
                    </p>
                  </div>
                </div>
                {unreadCounts.chatCounts[chat._id] > 0 && (
                  <Badge variant="destructive">
                    {unreadCounts.chatCounts[chat._id]} unread
                  </Badge>
                )}
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
} 