<x-admin-layout>
    <x-slot name="header">
        <div class="flex items-center justify-between">
            <h2 class="text-xl font-semibold text-gray-800">
                Chat with {{ $session->tenant->name ?? 'Unknown Tenant' }}
            </h2>
            <div class="flex items-center space-x-4">
                <a href="{{ route('admin.chat.index') }}" 
                   class="text-gray-600 hover:text-gray-800">
                    ← Back to Chat List
                </a>
                @if($session->status === 'active')
                    <form method="POST" action="{{ route('admin.chat.close', $session->id) }}" 
                          onsubmit="return confirm('Are you sure you want to close this chat session?')" class="inline">
                        @csrf
                        <button type="submit" class="bg-red-600 text-white px-4 py-2 rounded-md hover:bg-red-700 text-sm">
                            Close Chat
                        </button>
                    </form>
                @else
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                        Closed
                    </span>
                @endif
            </div>
        </div>
    </x-slot>

    <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <div class="bg-white shadow-sm rounded-lg">
            <!-- Chat Header -->
            <div class="p-4 border-b border-gray-200 bg-gray-50">
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <div class="h-10 w-10 rounded-full bg-blue-500 flex items-center justify-center">
                                <span class="text-white font-medium">
                                    {{ $session->tenant ? substr($session->tenant->name ?? '', 0, 1) : '?' }}
                                </span>
                            </div>
                        </div>
                        <div class="ml-3">
                            <h3 class="text-lg font-medium text-gray-900">{{ $session->tenant->name ?? 'Unknown Tenant' }}</h3>
                            <p class="text-sm text-gray-500">
                                Status: 
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                                    @if($session->status === 'active') bg-green-100 text-green-800
                                    @elseif($session->status === 'closed') bg-red-100 text-red-800
                                    @else bg-gray-100 text-gray-800 @endif">
                                    {{ ucfirst($session->status) }}
                                </span>
                                @if($session->started_at)
                                    • Started {{ $session->started_at->diffForHumans() }}
                                @endif
                            </p>
                        </div>
                    </div>
                    <div class="text-sm text-gray-500">
                        @if($session->last_message_at)
                            Last activity: {{ $session->last_message_at->diffForHumans() }}
                        @else
                            No messages yet
                        @endif
                    </div>
                </div>
            </div>

            <!-- Messages Area -->
            <div id="messagesContainer" class="h-96 overflow-y-auto p-4 space-y-4">
                @if($session->messages && $session->messages->count() > 0)
                    @foreach($session->messages as $message)
                        <div class="flex {{ $message->sender_type === 'admin' ? 'justify-end' : 'justify-start' }}">
                            <div class="max-w-xs lg:max-w-md">
                                <div class="{{ $message->sender_type === 'admin' ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-900' }} rounded-lg px-4 py-2">
                                    <p class="text-sm">{{ $message->message }}</p>
                                </div>
                                <p class="text-xs text-gray-500 mt-1 {{ $message->sender_type === 'admin' ? 'text-right' : 'text-left' }}">
                                    {{ $message->created_at->format('h:i A') }}
                                    @if($message->sender_type === 'admin')
                                        @if($message->is_read)
                                            <span class="text-green-500">✓✓</span>
                                        @else
                                            <span class="text-gray-400">✓</span>
                                        @endif
                                    @endif
                                </p>
                            </div>
                        </div>
                    @endforeach
                @else
                    <div class="text-center text-gray-500 py-8">
                        <svg class="w-12 h-12 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                        </svg>
                        <p class="text-sm">No messages yet. Start the conversation!</p>
                    </div>
                @endif
            </div>

            <!-- Message Input -->
            @if($session->status === 'active')
                <div class="p-4 border-t border-gray-200">
                    <form id="messageForm" class="flex space-x-2">
                        @csrf
                        <input type="hidden" name="session_id" value="{{ $session->id }}">
                        <input type="text" 
                               name="message" 
                               id="messageInput"
                               class="flex-1 rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-200 focus:ring-opacity-50" 
                               placeholder="Type your message..." 
                               maxlength="1000"
                               required>
                        <button type="submit" 
                                class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                            Send
                        </button>
                    </form>
                </div>
            @else
                <div class="p-4 border-t border-gray-200 bg-gray-50">
                    <p class="text-center text-gray-500 text-sm">
                        This chat session is closed. You cannot send messages.
                    </p>
                </div>
            @endif
        </div>
    </div>

    <script>
        let currentUserId = {{ Auth::id() }};
        let lastMessageId = 0;
        let isTyping = false;
        let typingTimeout;

        function scrollToBottom() {
            const container = document.getElementById('messagesContainer');
            container.scrollTop = container.scrollHeight;
        }

        // Scroll to bottom on page load
        window.addEventListener('load', scrollToBottom);

        // Handle message form submission
        document.getElementById('messageForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const input = document.getElementById('messageInput');
            const messageText = input.value.trim();
            
            if (!messageText) return;
            
            // Add message to UI immediately for better UX
            addMessageToUI({
                id: 'temp-' + Date.now(),
                message: messageText,
                sender_type: 'admin',
                sender_id: currentUserId,
                sender_name: 'You',
                is_read: false,
                read_at: null,
                created_at: new Date().toISOString(),
                formatted_time: new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}),
                timestamp: Date.now() / 1000
            });
            
            input.value = '';
            
            fetch('{{ route('admin.chat.send', $session->id) }}', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Remove temporary message and refresh
                    removeTemporaryMessage();
                    refreshMessages();
                } else {
                    alert('Failed to send message. Please try again.');
                    removeTemporaryMessage();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Failed to send message. Please try again.');
                removeTemporaryMessage();
            });
        });

        function addMessageToUI(message) {
            const container = document.getElementById('messagesContainer');
            const messageDiv = document.createElement('div');
            messageDiv.className = `flex ${message.sender_type === 'admin' ? 'justify-end' : 'justify-start'} mb-4`;
            messageDiv.setAttribute('data-message-id', message.id);
            
            const readStatus = message.sender_type === 'admin' 
                ? (message.is_read ? '<span class="text-green-500">✓✓</span>' : '<span class="text-gray-400">✓</span>')
                : '';
            
            messageDiv.innerHTML = `
                <div class="max-w-xs lg:max-w-md">
                    <div class="${message.sender_type === 'admin' ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-900'} rounded-lg px-4 py-2 shadow-sm">
                        <p class="text-sm">${message.message}</p>
                    </div>
                    <div class="flex items-center justify-between mt-2">
                        <p class="text-xs text-gray-500 ${message.sender_type === 'admin' ? 'text-right' : 'text-left'}">
                            ${message.formatted_time}
                            ${readStatus}
                        </p>
                        <div class="flex items-center ml-2">
                            <p class="text-xs text-gray-400 mr-2">
                                ${message.sender_name}
                            </p>
                            <p class="text-xs text-gray-300">
                                ${message.formatted_date}
                            </p>
                        </div>
                    </div>
                </div>
            `;
            
            container.appendChild(messageDiv);
            scrollToBottom();
        }

        function removeTemporaryMessage() {
            const tempMessage = document.querySelector('[data-message-id^="temp-"]');
            if (tempMessage) {
                tempMessage.remove();
            }
        }

        // Refresh messages
        function refreshMessages() {
            fetch('{{ route('admin.chat.messages', $session->id) }}')
                .then(response => response.json())
                .then(data => {
                    const container = document.getElementById('messagesContainer');
                    
                    // Clear existing messages
                    container.innerHTML = '';
                    
                    if (data.length === 0) {
                        container.innerHTML = `
                            <div class="text-center text-gray-500 py-8">
                                <svg class="w-12 h-12 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                                </svg>
                                <p class="text-sm">No messages yet. Start the conversation!</p>
                            </div>
                        `;
                    } else {
                        // Group messages by sender and time to create conversational flow
                        const groupedMessages = groupMessagesByConversation(data);
                        
                        groupedMessages.forEach(group => {
                            group.forEach(message => {
                                addMessageToUI(message);
                            });
                        });
                    }
                });
        }

        // Group messages to create conversational flow
        function groupMessagesByConversation(messages) {
            const groups = [];
            let currentGroup = [];
            let lastSenderType = null;
            let lastTimestamp = null;
            const TIME_GAP = 30000; // 30 seconds gap between messages from same sender
            
            messages.forEach(message => {
                const messageTimestamp = message.timestamp * 1000; // Convert to milliseconds
                const timeDiff = lastTimestamp ? messageTimestamp - lastTimestamp : 0;
                
                // Start new group if sender changes or time gap is too large
                if (lastSenderType !== message.sender_type || timeDiff > TIME_GAP) {
                    if (currentGroup.length > 0) {
                        groups.push(currentGroup);
                    }
                    currentGroup = [message];
                } else {
                    currentGroup.push(message);
                }
                
                lastSenderType = message.sender_type;
                lastTimestamp = messageTimestamp;
            });
            
            if (currentGroup.length > 0) {
                groups.push(currentGroup);
            }
            
            return groups;
        }

        // Real-time updates using polling (more reliable than SSE)
        let pollingInterval;
        
        function startRealTimeUpdates() {
            // Clear any existing interval
            if (pollingInterval) {
                clearInterval(pollingInterval);
            }
            
            // Poll for new messages every 2 seconds
            pollingInterval = setInterval(() => {
                checkForNewMessages();
            }, 2000);
            
            // Initial check
            checkForNewMessages();
        }
        
        function checkForNewMessages() {
            fetch('{{ route('admin.chat.stream', $session->id) }}?last_id=' + lastMessageId)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        console.error('Error:', data.error);
                        return;
                    }
                    
                    if (data.messages && data.messages.length > 0) {
                        data.messages.forEach(message => {
                            addMessageToUI(message);
                            if (message.id > lastMessageId) {
                                lastMessageId = message.id;
                            }
                        });
                    }
                })
                .catch(error => {
                    console.error('Polling error:', error);
                    // Don't show error to user, just log it
                });
        }
        
        function showTypingIndicator(sender) {
            // Implement typing indicator if needed
            console.log(sender + ' is typing...');
        }
        
        function updateReadStatus(messageId) {
            const messageElement = document.querySelector(`[data-message-id="${messageId}"]`);
            if (messageElement) {
                const readStatusElement = messageElement.querySelector('.text-gray-400');
                if (readStatusElement) {
                    readStatusElement.className = 'text-green-500';
                    readStatusElement.textContent = '✓✓';
                }
            }
        }
        
        function sendTypingIndicator() {
            fetch('{{ route('admin.chat.typing', $session->id) }}', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    typing: true,
                    sender_type: 'admin'
                })
            }).catch(error => {
                // Silently ignore typing indicator errors
            });
        }

        // Initialize real-time updates
        startRealTimeUpdates();
    </script>
</x-admin-layout>
