// app/support/tickets/[id]/page.js
'use client';
import { useState, useEffect, useRef } from 'react';
import { useSocket } from '@/context/SocketContext';
import { useParams } from 'next/navigation';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Send, Loader2 } from 'lucide-react';
import { useToast } from '@/hooks/useToast';
import { authFetch } from '@/lib/api';
import { useAuthStore } from '@/stores/authStore';

export default function SupportTicketPage() {
    const { id } = useParams();
    const { socket } = useSocket();
    const { toast } = useToast();
    const [messages, setMessages] = useState([]);
    const [message, setMessage] = useState('');
    const [ticket, setTicket] = useState(null);
    const [isLoading, setIsLoading] = useState(true);
    const messagesEndRef = useRef(null);
    const user = useAuthStore((state) => state.user);

    // Fetch ticket and messages
    useEffect(() => {
        const fetchData = async () => {
            try {
                const [ticketRes, messagesRes] = await Promise.all([
                    authFetch(`/api/support/tickets/${id}`),
                    authFetch(`/api/support/tickets/${id}/messages`)
                ]);
                console.log('Fetched ticket:', ticketRes);
                console.log('Fetched messages:', messagesRes);
                setTicket(ticketRes);
                setMessages(messagesRes);
            } catch (error) {
                toast({
                    title: 'Error',
                    description: error.message,
                    variant: 'destructive'
                });
            } finally {
                setIsLoading(false);
            }
        };

        fetchData();
    }, [id, toast]);

    // Socket event listeners
    useEffect(() => {
        if (!socket) return;

        // Join the ticket room
        socket.emit('join-ticket', { ticketId: id });

        // Handle new messages
        const handleNewMessage = (newMessage) => {
            setMessages(prev => [...prev, newMessage]);
        };

        socket.on('new-message', handleNewMessage);

        return () => {
            socket.off('new-message', handleNewMessage);
        };
    }, [socket, id]);

    // Auto-scroll to bottom when messages change
    useEffect(() => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [messages]);

    const sendMessage = async () => {
        if (!message.trim()) return;
        const tempId = Date.now().toString();
        try {
            // Optimistically add message to UI

            console.log('Optimistic message ID:', tempId);
            // const newMessage = {
            //     id: tempId,
            //     content: message,
            //     senderId: user.id,
            //     createdAt: new Date().toISOString(),
            //     isOptimistic: true
            // };

            // console.log(newMessage)

            // setMessages(prev => [...prev, newMessage]);
            setMessage('');

            // Send message to server
            const response = await authFetch(`/api/support/tickets/${id}/messages`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ content: message })
            });

            // Replace optimistic message with real one
            setMessages(prev => prev.map(msg =>
                msg.id === tempId ? response : msg
            ));

            // Emit socket event
            socket.emit('send-support-message', {
                ticketId: id,
                message: response
            });

        } catch (error) {
            // Remove optimistic message if error
            setMessages(prev => prev.filter(msg => msg.id !== tempId));
            toast({
                title: 'Error',
                description: error.message,
                variant: 'destructive'
            });
        }
    };

    if (isLoading) {
        return (
            <div className="flex items-center justify-center h-64">
                <Loader2 className="h-8 w-8 animate-spin" />
            </div>
        );
    }

    if (!ticket) {
        return (
            <div className="p-4 text-center">
                <h2 className="text-xl font-semibold">Ticket not found</h2>
            </div>
        );
    }

    return (
        <div className="container mx-auto p-4 flex flex-col h-screen max-w-4xl">
            <div className="border-b pb-4 mb-4">
                <h1 className="text-2xl font-bold">Support Ticket #{ticket.id.slice(0, 6)}</h1>
                <p className="text-gray-600">{ticket.subject}</p>
            </div>
            {messages.length === 0 &&
                <div className="flex items-center justify-center h-full">
                    <p className="text-gray-500">No messages yet. Start the conversation!</p>
                </div>
            }
            {messages.length > 0 &&
                <div className="flex-1 overflow-y-auto mb-4 space-y-4">
                    {messages.map((msg) => (
                        <div
                            key={msg.id}
                            className={`flex ${msg.senderId === user.id ? 'justify-end' : 'justify-start'}`}
                        >
                            <div
                                className={`max-w-[80%] rounded-lg p-3 ${msg.senderId === user.id
                                    ? 'bg-blue-500 text-white'
                                    : 'bg-gray-100 text-gray-900'
                                    }`}
                            >
                                <p>{msg.content}</p>
                                <p className={`text-xs mt-1 ${msg.senderId === user.id ? 'text-blue-100' : 'text-gray-500'
                                    }`}>
                                    {new Date(msg.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                                </p>
                            </div>
                        </div>
                    ))}
                    <div ref={messagesEndRef} />
                </div>
            }
            <div className="flex gap-2">
                <Input
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    onKeyDown={(e) => e.key === 'Enter' && sendMessage()}
                    placeholder="Type your message..."
                />
                <Button onClick={sendMessage}>
                    <Send className="h-4 w-4" />
                </Button>
            </div>
        </div>
    );
}