"use client"

import React, { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { cn } from "@/lib/utils";
import { formatDistanceToNow } from "date-fns";
import axios from "axios";
import { toast } from "sonner";
import { ArrowLeft, Send, RefreshCw, File, FileText, Image as ImageIcon, Download } from "lucide-react";
import { getCookie } from "@/lib/client-utils";

interface Message {
  _id: string;
  sender: "buyer" | "vendor";
  content: string;
  attachments: string[];
  read: boolean;
  createdAt: string;
  buyerId: string;
  vendorId: string;
}

interface Chat {
  _id: string;
  buyerId: string;
  vendorId: string;
  storeId: string;
  messages: Message[];
  lastUpdated: string;
  orderId?: string;
}

// Helper function to extract filename from URL
const getFileNameFromUrl = (url: string): string => {
  // Try to extract filename from the URL path
  const pathParts = url.split('/');
  const lastPart = pathParts[pathParts.length - 1];
  
  // Remove query parameters if any
  const fileNameParts = lastPart.split('?');
  let fileName = fileNameParts[0];
  
  // If filename is too long or not found, create a generic name
  if (!fileName || fileName.length > 30) {
    return 'attachment';
  }
  
  // URL decode the filename (handle spaces and special characters)
  try {
    fileName = decodeURIComponent(fileName);
  } catch (e) {
    // If decoding fails, use the original
  }
  
  return fileName;
};

// Helper function to get file icon based on extension or URL pattern
const getFileIcon = (url: string): React.ReactNode => {
  const fileName = url.toLowerCase();
  
  // Image files
  if (/\.(jpg|jpeg|png|gif|webp|svg|bmp|tiff)($|\?)/i.test(fileName) || 
      url.includes('/photos/') || url.includes('/photo/')) {
    return <ImageIcon className="h-5 w-5" />;
  }
  
  // Document files
  if (/\.(pdf|doc|docx|xls|xlsx|ppt|pptx|txt|rtf|csv)($|\?)/i.test(fileName)) {
    return <FileText className="h-5 w-5" />;
  }
  
  // Default file icon
  return <File className="h-5 w-5" />;
};

export default function ChatDetail({ chatId }: { chatId: string }) {
  const router = useRouter();
  const [chat, setChat] = useState<Chat | null>(null);
  const [loading, setLoading] = useState(true);
  const [message, setMessage] = useState("");
  const [sending, setSending] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const [previousMessageCount, setPreviousMessageCount] = useState<number>(0);
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const markReadTimeoutRef = useRef<NodeJS.Timeout | 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;
      }
      
      // Clear any pending timeouts when component unmounts
      if (markReadTimeoutRef.current) {
        clearTimeout(markReadTimeoutRef.current);
      }
    };
  }, []);
  
  // 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);
      }
    }
  };
  
  // Function to mark messages as read
  const markMessagesAsRead = async () => {
    try {
      const authToken = getCookie("Authorization");
      
      if (!authToken) return;
      
      const authAxios = axios.create({
        baseURL: process.env.NEXT_PUBLIC_API_URL,
        headers: {
          Authorization: `Bearer ${authToken}`
        }
      });
      
      // Use dedicated endpoint to mark messages as read
      await authAxios.post(`/chats/${chatId}/mark-read`);
      console.log("Marked messages as read");
    } catch (error) {
      console.error("Error marking messages as read:", error);
    }
  };
  
  // Fetch chat data
  const fetchChat = async () => {
    try {
      // Get auth token from cookies
      const authToken = getCookie("Authorization");
      
      if (!authToken) {
        toast.error("You need to be logged in");
        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}`
        }
      });
      
      // Always fetch messages without marking as read
      const response = await authAxios.get(`/chats/${chatId}?markAsRead=false`);
      
      // Check if there are new messages
      const hasNewMessages = chat && response.data.messages.length > chat.messages.length;
      const unreadBuyerMessages = response.data.messages.some(
        (msg: Message) => msg.sender === 'buyer' && !msg.read
      );
      
      if (hasNewMessages) {
        // Don't play sound for messages we sent (vendor)
        const lastMessage = response.data.messages[response.data.messages.length - 1];
        if (lastMessage.sender === 'buyer') {
          playNotificationSound();
        }
      }
      
      setChat(response.data);
      
      // Update the previous message count
      if (response.data.messages) {
        setPreviousMessageCount(response.data.messages.length);
      }
      
      setLoading(false);
      
      // Clear any existing timeout
      if (markReadTimeoutRef.current) {
        clearTimeout(markReadTimeoutRef.current);
      }
      
      // Only mark as read with a delay if there are unread buyer messages
      if (unreadBuyerMessages) {
        // Add a 3-second delay before marking messages as read to allow notification to appear
        markReadTimeoutRef.current = setTimeout(() => {
          markMessagesAsRead();
        }, 3000);
      }
    } catch (error) {
      console.error("Error fetching chat:", error);
      toast.error("Failed to load conversation");
      setLoading(false);
    }
  };
  
  useEffect(() => {
    fetchChat();
    
    // Poll for updates every 10 seconds
    const intervalId = setInterval(fetchChat, 10000);
    
    return () => clearInterval(intervalId);
  }, [chatId]);
  
  // Scroll to bottom when messages change
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [chat?.messages]);
  
  // Send a message
  const handleSendMessage = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!message.trim()) return;
    
    setSending(true);
    try {
      // Get auth token from cookies
      const authToken = getCookie("Authorization");
      
      if (!authToken) {
        toast.error("You need to be logged in");
        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}`
        }
      });
      
      await authAxios.post(`/chats/${chatId}/message`, {
        content: message
      });
      
      setMessage("");
      await fetchChat(); // Refresh chat after sending
    } catch (error) {
      console.error("Error sending message:", error);
      toast.error("Failed to send message");
    } finally {
      setSending(false);
    }
  };
  
  const handleBackClick = () => {
    router.push("/dashboard/chats");
  };
  
  if (loading) {
    return (
      <div className="flex flex-col h-screen w-full relative">
        <div className="border-b py-2 px-4 flex items-center space-x-2 bg-card z-10">
          <Button variant="ghost" size="icon" onClick={handleBackClick}>
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <span className="text-lg font-semibold">Loading conversation...</span>
        </div>
        <div className="flex-1 flex items-center justify-center">
          <RefreshCw className="h-8 w-8 animate-spin text-muted-foreground" />
        </div>
      </div>
    );
  }
  
  if (!chat) {
    return (
      <div className="flex flex-col h-screen w-full relative">
        <div className="border-b py-2 px-4 flex items-center space-x-2 bg-card z-10">
          <Button variant="ghost" size="icon" onClick={handleBackClick}>
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <span className="text-lg font-semibold">Chat not found</span>
        </div>
        <div className="flex-1 flex items-center justify-center">
          <div className="text-center">
            <p className="text-muted-foreground mb-4">This conversation doesn't exist or you don't have access to it.</p>
            <Button onClick={handleBackClick}>Back to Chats</Button>
          </div>
        </div>
      </div>
    );
  }
  
  return (
    <div className="flex flex-col h-screen w-full relative">
      <div className="border-b py-2 px-4 flex items-center space-x-2 bg-card z-10">
        <Button variant="ghost" size="icon" onClick={handleBackClick}>
          <ArrowLeft className="h-5 w-5" />
        </Button>
        <h3 className="text-lg font-semibold">Chat with Customer {chat.buyerId.slice(-4)}</h3>
      </div>
      
      <div className="flex-1 overflow-y-auto p-2 space-y-2 pb-[58px]">
        {chat.messages.length === 0 ? (
          <div className="h-full flex items-center justify-center">
            <p className="text-muted-foreground">No messages yet. Send one to start the conversation.</p>
          </div>
        ) : (
          chat.messages.map((msg, index) => (
            <div
              key={msg._id || index}
              className={cn(
                "flex",
                msg.sender === "vendor" ? "justify-end" : "justify-start"
              )}
            >
              <div
                className={cn(
                  "max-w-[90%] rounded-lg p-3",
                  msg.sender === "vendor"
                    ? "bg-primary text-primary-foreground"
                    : "bg-muted"
                )}
              >
                <div className="flex items-center space-x-2 mb-1">
                  {msg.sender === "buyer" && (
                    <Avatar className="h-6 w-6">
                      <AvatarFallback className="text-xs">
                        {chat.buyerId.slice(0, 2).toUpperCase()}
                      </AvatarFallback>
                    </Avatar>
                  )}
                  <span className="text-xs opacity-70">
                    {formatDistanceToNow(new Date(msg.createdAt), { addSuffix: true })}
                  </span>
                </div>
                <p className="whitespace-pre-wrap break-words">{msg.content}</p>
                {/* Show attachments if any */}
                {msg.attachments && msg.attachments.length > 0 && (
                  <div className="mt-2 space-y-2">
                    {msg.attachments.map((attachment, idx) => {
                      // Check if attachment is an image by looking at the URL extension or paths
                      const isImage = /\.(jpg|jpeg|png|gif|webp)($|\?)/i.test(attachment) || 
                                      attachment.includes('/photos/') || 
                                      attachment.includes('/photo/');
                      
                      const fileName = getFileNameFromUrl(attachment);
                      
                      return isImage ? (
                        // Render image attachment
                        <div key={`attachment-${idx}`} className="rounded-md overflow-hidden bg-background/20 p-1">
                          <div className="flex justify-between items-center mb-1">
                            <span className="text-xs opacity-70 flex items-center">
                              <ImageIcon className="h-3 w-3 mr-1" />
                              {fileName}
                            </span>
                            <a 
                              href={attachment} 
                              download={fileName}
                              target="_blank" 
                              rel="noopener noreferrer"
                              className="text-xs opacity-70 hover:opacity-100"
                              onClick={(e) => e.stopPropagation()}
                            >
                              <Download className="h-3 w-3" />
                            </a>
                          </div>
                          <a href={attachment} target="_blank" rel="noopener noreferrer">
                            <img 
                              src={attachment} 
                              alt={fileName} 
                              className="max-w-full max-h-60 object-contain cursor-pointer hover:opacity-90 transition-opacity rounded"
                              onError={(e) => {
                                // Fallback for broken images
                                (e.target as HTMLImageElement).src = "/placeholder-image.svg";
                              }}
                            />
                          </a>
                        </div>
                      ) : (
                        // Render file attachment
                        <div key={`attachment-${idx}`} className="flex items-center bg-background/20 rounded-md p-2 hover:bg-background/30 transition-colors">
                          <div className="mr-2">
                            {getFileIcon(attachment)}
                          </div>
                          <div className="flex-1 min-w-0">
                            <div className="text-sm truncate font-medium">
                              {fileName}
                            </div>
                          </div>
                          <a 
                            href={attachment} 
                            download={fileName}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="ml-2 p-1 rounded-sm hover:bg-background/50"
                          >
                            <Download className="h-4 w-4" />
                          </a>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            </div>
          ))
        )}
        <div ref={messagesEndRef} />
      </div>
      
      <div className="absolute bottom-0 left-0 right-0 border-t border-border bg-background p-4">
        <form onSubmit={handleSendMessage} className="flex space-x-2">
          <Input
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            placeholder="Type your message..."
            disabled={sending}
            className="flex-1"
          />
          <Button type="submit" disabled={sending || !message.trim()}>
            {sending ? <RefreshCw className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
          </Button>
        </form>
      </div>
    </div>
  );
} 