// components/SupportChat/SupportChatWindow.js
'use client';
import { useEffect, useRef, useState, useCallback } from 'react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { X, Send } from 'lucide-react';
import { useSocket } from '@/context/SocketContext';
import { useAuthStore } from '@/stores/authStore';

export default function SupportChatWindow({ onClose }) {
    const [messages, setMessages] = useState([]);
    const [message, setMessage] = useState('');
    const [status, setStatus] = useState('Connecting...');
    const [room, setRoom] = useState(null);
    const [agent, setAgent] = useState(null);
    const messagesEndRef = useRef(null);
    const { socket, isConnected } = useSocket();

    const userData = useAuthStore((state) => state.user);

    const user = userData?.profile || null;

    // Memoized event handlers
    const handleSupportStatus = useCallback((data) => {
        setStatus(data.message);
        if (data.room) setRoom(data.room);
    }, []);

    const handleSupportAccepted = useCallback((data) => {
        setAgent({ id: data.agentId, name: data.agentName });
        setStatus(`Connected with ${data.agentName}`);
        setRoom(`user_support_${socket.user.id}`);
    }, [socket?.user?.id]);

    const handleNewMessage = useCallback((msg) => {
        setMessages(prev => [...prev, msg]);
    }, []);

    const handleSupportEnded = useCallback((data) => {
        setStatus(data.message);
        setTimeout(onClose, 3000);
    }, [onClose]);

    const handleSupportError = useCallback((error) => {
        setStatus(`Error: ${error.error}`);
    }, []);

    // Join support effect
    useEffect(() => {
        console.log('SupportChatWindow mounted')
        if (!socket) return;

        const joinSupport = () => {
            console.log('Joining support...');
            socket.emit('join-support');
        };

        if (isConnected) {
            joinSupport();
        } else {
            const handleConnect = () => {
                joinSupport();
                socket.off('connect', handleConnect);
            };
            socket.on('connect', handleConnect);
        }

        // Set up all event listeners
        socket.on('support-status', handleSupportStatus);
        socket.on('support-accepted', handleSupportAccepted);
        socket.on('new-support-message', handleNewMessage);
        socket.on('support-ended', handleSupportEnded);
        socket.on('support-error', handleSupportError);

        return () => {
            // Clean up all listeners
            socket.off('support-status', handleSupportStatus);
            socket.off('support-accepted', handleSupportAccepted);
            socket.off('new-support-message', handleNewMessage);
            socket.off('support-ended', handleSupportEnded);
            socket.off('support-error', handleSupportError);

            if (room) {
                socket.emit('end-support-session', { room });
            }
        };
    }, [
        socket,
        isConnected,
        room,
        handleSupportStatus,
        handleSupportAccepted,
        handleNewMessage,
        handleSupportEnded,
        handleSupportError
    ]);

    useEffect(() => {
        scrollToBottom();
    }, [messages]);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    };

    const handleSendMessage = () => {
        if (message.trim() && room) {
            socket.emit('send-support-message', {
                room,
                content: message
            });
            setMessage('');
        }
    };

    return (
        <div className="fixed bottom-24 right-6 w-80 bg-white rounded-lg shadow-xl border border-gray-200 flex flex-col z-50">
            <div className="bg-blue-600 text-white p-3 rounded-t-lg flex justify-between items-center">
                <h3 className="font-semibold">Support Chat</h3>
                <button onClick={onClose} className="text-white hover:text-gray-200">
                    <X className="h-5 w-5" />
                </button>
            </div>


            <div className="p-3 text-sm text-gray-500 border-b flex items-center gap-2">
                <span className={`inline-block w-2 h-2 rounded-full ${isConnected ? 'bg-green-500' : 'bg-red-500'
                    }`}></span>
                {status}
            </div>

            <div className="flex-1 p-3 overflow-y-auto max-h-80">
                {messages.map((msg, i) => (
                    <div
                        key={i}
                        className={`mb-2 ${msg.senderId === user.userId ? 'text-right' : 'text-left'}`}
                    >
                        <div className={`inline-block p-2 rounded-lg ${msg.senderId === user.userId ? 'bg-blue-100 text-blue-900' : 'bg-gray-100 text-gray-900'}`}>
                            {msg.content}
                        </div>
                        <div className="text-xs text-gray-500 mt-1">
                            {msg.senderId === user.userId ? 'You' : msg.senderName} • {new Date(msg.timestamp).toLocaleTimeString()}
                        </div>
                    </div>
                ))}
                <div ref={messagesEndRef} />
            </div>

            <div className="p-3 border-t flex gap-2">
                <Input
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()}
                    placeholder="Type your message..."
                    disabled={!room}
                />
                <Button
                    onClick={handleSendMessage}
                    disabled={!room || !message.trim()}
                >
                    <Send className="h-4 w-4" />
                </Button>
            </div>
        </div>
    );
}