<x-admin.layout :title="($conversation->title ?? 'New Conversation').' - AI Chat'">
    <div class="grid grid-cols-1 lg:grid-cols-4 gap-6">
        <!-- Conversation Info -->
        <div class="lg:col-span-1">
            <x-admin.card title="Conversation Details">
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Title</label>
                        <p class="text-sm text-gray-900 dark:text-white">
                            {{ $conversation->title ?? 'Untitled Conversation' }}
                        </p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">User</label>
                        <p class="text-sm text-gray-900 dark:text-white">
                            {{ $conversation->user?->name ?? 'Admin' }}
                        </p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Created</label>
                        <p class="text-sm text-gray-500 dark:text-gray-400">
                            {{ $conversation->created_at->format('M d, Y H:i') }}
                        </p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Last Activity</label>
                        <p class="text-sm text-gray-500 dark:text-gray-400">
                            {{ $conversation->last_message_at?->diffForHumans() ?? 'Never' }}
                        </p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Messages</label>
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
                            {{ $messages->count() }}
                        </span>
                    </div>

                    <hr class="border-gray-200 dark:border-gray-700">

                    <div class="flex gap-2">
                        <a href="{{ route('admin.ai-chat.index') }}" class="flex-1 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-2 px-4 rounded-lg transition-colors text-center dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600">
                            Back
                        </a>
                        <form action="{{ route('admin.ai-chat.delete', $conversation->ulid) }}" method="POST" class="flex-1" onsubmit="return confirm('Are you sure you want to delete this conversation?');">
                            @csrf
                            @method('DELETE')
                            <button type="submit" class="w-full bg-red-100 hover:bg-red-200 text-red-700 font-medium py-2 px-4 rounded-lg transition-colors dark:bg-red-900 dark:text-red-200 dark:hover:bg-red-800">
                                Delete
                            </button>
                        </form>
                    </div>
                </div>
            </x-admin.card>
        </div>

        <!-- Chat Interface -->
        <div class="lg:col-span-3">
            <x-admin.card>
                <div class="flex flex-col h-[calc(100vh-200px)] min-h-[500px]">
                    <!-- Messages Container -->
                    <div id="messages-container" class="flex-1 overflow-y-auto space-y-4 p-4 bg-gray-50 dark:bg-gray-900 rounded-lg">
                        @forelse($messages as $message)
                            <div class="flex {{ $message->role === 'user' ? 'justify-end' : 'justify-start' }}">
                                <div class="max-w-[80%] rounded-lg px-4 py-3 {{ $message->role === 'user' ? 'bg-blue-600 text-white' : 'bg-white dark:bg-gray-800 text-gray-900 dark:text-white border border-gray-200 dark:border-gray-700' }}">
                                    <div class="flex items-center gap-2 mb-2">
                                        <span class="text-xs font-semibold {{ $message->role === 'user' ? 'text-blue-200' : 'text-gray-500 dark:text-gray-400' }}">
                                            {{ $message->role === 'user' ? 'You' : 'AI Assistant' }}
                                        </span>
                                        <span class="text-xs {{ $message->role === 'user' ? 'text-blue-200' : 'text-gray-400' }}">
                                            {{ $message->created_at->format('H:i') }}
                                        </span>
                                    </div>
                                    <div class="text-sm whitespace-pre-wrap">
                                        {!! nl2br(e($message->content)) !!}
                                    </div>

                                    @if($message->tool_calls && count($message->tool_calls) > 0)
                                        <div class="mt-2 pt-2 border-t {{ $message->role === 'user' ? 'border-blue-400' : 'border-gray-200 dark:border-gray-700' }}">
                                            <p class="text-xs {{ $message->role === 'user' ? 'text-blue-200' : 'text-gray-500 dark:text-gray-400' }} mb-1">Tools Used:</p>
                                            <div class="flex flex-wrap gap-1">
                                                @foreach($message->tool_calls as $tool)
                                                    <span class="text-xs px-2 py-1 rounded {{ $message->role === 'user' ? 'bg-blue-500' : 'bg-gray-200 dark:bg-gray-700' }} {{ $message->role === 'user' ? 'text-white' : 'text-gray-700 dark:text-gray-300' }}">
                                                        {{ $tool['name'] }}
                                                    </span>
                                                @endforeach
                                            </div>
                                        </div>
                                    @endif
                                </div>
                            </div>
                        @empty
                            <div class="flex items-center justify-center h-full">
                                <div class="text-center text-gray-500 dark:text-gray-400">
                                    <svg class="w-16 h-16 mx-auto mb-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
                                    </svg>
                                    <p>No messages yet. Start the conversation!</p>
                                </div>
                            </div>
                        @endforelse
                    </div>

                    <!-- Message Input -->
                    <div class="mt-4 border-t border-gray-200 dark:border-gray-700 pt-4">
                        <form id="chat-form" action="{{ route('admin.ai-chat.stream', $conversation->ulid) }}" method="POST">
                            @csrf
                            <div class="flex gap-2">
                                <input
                                    type="text"
                                    id="message-input"
                                    name="message"
                                    placeholder="Type your message..."
                                    class="flex-1 rounded-lg border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                    required
                                    autocomplete="off"
                                >
                                <button
                                    type="submit"
                                    id="send-button"
                                    class="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed text-white font-medium py-2 px-6 rounded-lg transition-colors"
                                >
                                    Send
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </x-admin.card>
        </div>
    </div>

    <script>
        // Auto-scroll to bottom of messages
        function scrollToBottom() {
            const container = document.getElementById('messages-container');
            if (container) {
                container.scrollTop = container.scrollHeight;
            }
        }

        // Initial scroll
        scrollToBottom();

        // Handle streaming response
        document.getElementById('chat-form').addEventListener('submit', async (e) => {
            e.preventDefault();

            const form = e.target;
            const input = document.getElementById('message-input');
            const button = document.getElementById('send-button');
            const container = document.getElementById('messages-container');
            const message = input.value.trim();

            if (!message) return;

            // Disable input and button
            input.disabled = true;
            button.disabled = true;
            button.textContent = 'Sending...';

            // Add user message
            const userMessageDiv = document.createElement('div');
            userMessageDiv.className = 'flex justify-end';
            userMessageDiv.innerHTML = `
                <div class="max-w-[80%] rounded-lg px-4 py-3 bg-blue-600 text-white">
                    <div class="flex items-center gap-2 mb-2">
                        <span class="text-xs font-semibold text-blue-200">You</span>
                        <span class="text-xs text-blue-200">${new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })}</span>
                    </div>
                    <div class="text-sm whitespace-pre-wrap">${message}</div>
                </div>
            `;
            container.appendChild(userMessageDiv);
            scrollToBottom();

            // Create assistant message placeholder
            const assistantMessageDiv = document.createElement('div');
            assistantMessageDiv.className = 'flex justify-start';
            const messageId = 'msg-' + Date.now();
            assistantMessageDiv.innerHTML = `
                <div class="max-w-[80%] rounded-lg px-4 py-3 bg-white dark:bg-gray-800 text-gray-900 dark:text-white border border-gray-200 dark:border-gray-700">
                    <div class="flex items-center gap-2 mb-2">
                        <span class="text-xs font-semibold text-gray-500 dark:text-gray-400">AI Assistant</span>
                        <span class="text-xs text-gray-400">${new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })}</span>
                    </div>
                    <div class="text-sm whitespace-pre-wrap" id="${messageId}">
                        <span class="inline-block animate-pulse">Thinking...</span>
                    </div>
                </div>
            `;
            container.appendChild(assistantMessageDiv);
            scrollToBottom();

            // Get reference to content div
            const contentDiv = assistantMessageDiv.querySelector(`#${messageId}`);

            // Clear input
            input.value = '';

            try {
                const response = await fetch(form.action, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'text/event-stream',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify({ message })
                });

                if (!response.ok) {
                    throw new Error(`Server returned ${response.status}: ${response.statusText}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let fullContent = '';
                let toolCalls = [];
                let hasReceivedContent = false;

                // Set timeout to detect if AI is not responding
                const timeout = setTimeout(() => {
                    if (!hasReceivedContent) {
                        contentDiv.innerHTML = `<span class="text-yellow-500">AI is taking longer than expected to respond. Please wait or try again.</span>`;
                    }
                }, 30000); // 30 seconds timeout

                // Clear thinking indicator on first content
                contentDiv.innerHTML = '';

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');

                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(line.slice(6));

                                if (data.type === 'content') {
                                    hasReceivedContent = true;
                                    clearTimeout(timeout);
                                    fullContent += data.content;
                                    contentDiv.innerHTML += data.content;
                                    scrollToBottom();
                                } else if (data.type === 'tool_call') {
                                    hasReceivedContent = true;
                                    clearTimeout(timeout);
                                    toolCalls.push(data.tool);
                                } else if (data.type === 'done') {
                                    // Show tool calls if any
                                    if (toolCalls.length > 0) {
                                        const toolsDiv = document.createElement('div');
                                        toolsDiv.className = 'mt-2 pt-2 border-t border-gray-200 dark:border-gray-700';
                                        toolsDiv.innerHTML = `
                                            <p class="text-xs text-gray-500 dark:text-gray-400 mb-1">Tools Used:</p>
                                            <div class="flex flex-wrap gap-1">
                                                ${toolCalls.map(tool => `
                                                    <span class="text-xs px-2 py-1 rounded bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300">
                                                        ${tool}
                                                    </span>
                                                `).join('')}
                                            </div>
                                        `;
                                        contentDiv.parentElement.appendChild(toolsDiv);
                                    }
                                } else if (data.type === 'error') {
                                    clearTimeout(timeout);
                                    contentDiv.innerHTML = `<span class="text-red-500">Error: ${data.error}</span>`;
                                }
                            } catch (e) {
                                console.error('Failed to parse SSE data:', e, line);
                            }
                        }
                    }
                }

                clearTimeout(timeout);
            } catch (error) {
                console.error('Stream error:', error);
                contentDiv.innerHTML = `<span class="text-red-500">Error: ${error.message}</span>`;
            } finally {
                // Re-enable input and button
                input.disabled = false;
                button.disabled = false;
                button.textContent = 'Send';
                input.focus();
            }
        });

        // Allow Enter key to submit
        document.getElementById('message-input').addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                document.getElementById('chat-form').dispatchEvent(new Event('submit'));
            }
        });
    </script>
</x-admin.layout>
