"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 } 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;
}

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);
  
  // 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}`
        }
      });
      
      const response = await authAxios.get(`/api/chats/${chatId}`);
      setChat(response.data);
      setLoading(false);
    } 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(`/api/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 (
      <Card className="w-full h-[80vh] flex flex-col">
        <CardHeader>
          <CardTitle className="flex items-center space-x-2">
            <Button variant="ghost" size="icon" onClick={handleBackClick}>
              <ArrowLeft className="h-5 w-5" />
            </Button>
            <span>Loading conversation...</span>
          </CardTitle>
        </CardHeader>
        <CardContent className="flex-1 flex items-center justify-center">
          <RefreshCw className="h-8 w-8 animate-spin text-muted-foreground" />
        </CardContent>
      </Card>
    );
  }
  
  if (!chat) {
    return (
      <Card className="w-full h-[80vh] flex flex-col">
        <CardHeader>
          <CardTitle className="flex items-center space-x-2">
            <Button variant="ghost" size="icon" onClick={handleBackClick}>
              <ArrowLeft className="h-5 w-5" />
            </Button>
            <span>Chat not found</span>
          </CardTitle>
        </CardHeader>
        <CardContent 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>
        </CardContent>
      </Card>
    );
  }
  
  return (
    <Card className="w-full h-[80vh] flex flex-col">
      <CardHeader className="border-b">
        <CardTitle className="flex items-center space-x-2">
          <Button variant="ghost" size="icon" onClick={handleBackClick}>
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <span>Chat with Customer {chat.buyerId.slice(-4)}</span>
        </CardTitle>
      </CardHeader>
      
      <CardContent className="flex-1 overflow-y-auto p-4 space-y-4">
        {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-[80%] 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 (future enhancement) */}
              </div>
            </div>
          ))
        )}
        <div ref={messagesEndRef} />
      </CardContent>
      
      <div className="p-4 border-t">
        <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>
    </Card>
  );
} 