{# app/templates/admin/messages.html #}
{% extends "admin/base.html" %}
{% from 'shared/macros/headers.html' import page_header_flex %}
{% from 'shared/macros/alerts.html' import loading_state, error_state %}
{% from 'shared/macros/modals.html' import form_modal, confirm_modal %}

{% block title %}Messages{% endblock %}

{% block alpine_data %}adminMessages({{ conversation_id or 'null' }}){% endblock %}

{% block content %}
{% call page_header_flex(title='Messages') %}
<button @click="showComposeModal = true"
        class="flex items-center px-4 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-purple-600 border border-transparent rounded-lg hover:bg-purple-700 focus:outline-none focus:shadow-outline-purple">
    <span x-html="$icon('plus', 'w-4 h-4 mr-2')"></span>
    New Conversation
</button>
{% endcall %}

{{ loading_state('Loading conversations...') }}

{{ error_state('Error loading conversations') }}

<!-- Main Messages Layout -->
<div x-show="!loading" class="flex gap-6 h-[calc(100vh-220px)]">
    <!-- Conversations List (Left Panel) -->
    <div class="w-96 flex-shrink-0 flex flex-col bg-white rounded-lg shadow-md dark:bg-gray-800 overflow-hidden">
        <!-- Filters -->
        <div class="p-4 border-b border-gray-200 dark:border-gray-700">
            <div class="flex gap-2">
                <select
                    x-model="filters.conversation_type"
                    @change="page = 1; loadConversations()"
                    class="flex-1 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
                >
                    <option value="">All Types</option>
                    <option value="admin_store">Stores</option>
                    <option value="admin_customer">Customers</option>
                </select>
                <select
                    x-model="filters.is_closed"
                    @change="page = 1; loadConversations()"
                    class="flex-1 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
                >
                    <option value="">All Status</option>
                    <option value="false">Open</option>
                    <option value="true">Closed</option>
                </select>
            </div>
        </div>

        <!-- Conversation List -->
        <div class="flex-1 overflow-y-auto">
            <template x-if="loadingConversations && conversations.length === 0">
                <div class="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
                    <span x-html="$icon('spinner', 'w-6 h-6 mx-auto mb-2 animate-spin')"></span>
                    <p>Loading...</p>
                </div>
            </template>

            <template x-if="!loadingConversations && conversations.length === 0">
                <div class="px-4 py-12 text-center text-gray-500 dark:text-gray-400">
                    <span x-html="$icon('chat-bubble-left-right', 'w-12 h-12 mx-auto mb-3 text-gray-300')"></span>
                    <p class="font-medium">No conversations</p>
                    <p class="text-sm mt-1">Start a new conversation</p>
                </div>
            </template>

            <ul class="divide-y divide-gray-200 dark:divide-gray-700">
                <template x-for="conv in conversations" :key="conv.id">
                    <li
                        @click="selectConversation(conv.id)"
                        class="px-4 py-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                        :class="{
                            'bg-purple-50 dark:bg-purple-900/20': selectedConversationId === conv.id,
                            'border-l-4 border-purple-500': selectedConversationId === conv.id
                        }"
                    >
                        <div class="flex items-start justify-between">
                            <div class="flex-1 min-w-0">
                                <div class="flex items-center gap-2">
                                    <span class="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate" x-text="conv.subject"></span>
                                    <span x-show="conv.unread_count > 0"
                                          class="px-2 py-0.5 text-xs bg-red-100 text-red-600 rounded-full dark:bg-red-600 dark:text-white"
                                          x-text="conv.unread_count"></span>
                                </div>
                                <div class="flex items-center gap-2 mt-1">
                                    <span class="inline-flex items-center px-1.5 py-0.5 text-xs rounded"
                                          :class="conv.conversation_type === 'admin_store' ? 'bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300' : 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300'"
                                          x-text="conv.conversation_type === 'admin_store' ? 'Store' : 'Customer'"></span>
                                    <span class="text-xs text-gray-500 dark:text-gray-400 truncate" x-text="conv.other_participant?.name || 'Unknown'"></span>
                                </div>
                                <p x-show="conv.last_message_preview"
                                   class="text-xs text-gray-500 dark:text-gray-400 mt-1 truncate"
                                   x-text="conv.last_message_preview"></p>
                            </div>
                            <div class="flex flex-col items-end ml-2">
                                <span class="text-xs text-gray-400" x-text="formatRelativeTime(conv.last_message_at || conv.created_at)"></span>
                                <span x-show="conv.is_closed"
                                      class="mt-1 px-1.5 py-0.5 text-xs bg-gray-100 text-gray-500 rounded dark:bg-gray-700">
                                    Closed
                                </span>
                            </div>
                        </div>
                    </li>
                </template>
            </ul>
        </div>

        <!-- Pagination -->
        <div x-show="totalConversations > limit" class="p-3 border-t border-gray-200 dark:border-gray-700">
            <div class="flex items-center justify-between text-sm">
                <span class="text-gray-500 dark:text-gray-400" x-text="`${skip + 1}-${Math.min(skip + limit, totalConversations)} of ${totalConversations}`"></span>
                <div class="flex gap-1">
                    <button @click="page--; loadConversations()" :disabled="page <= 1"
                            class="px-2 py-1 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded disabled:opacity-50">
                        <span x-html="$icon('chevron-left', 'w-4 h-4')"></span>
                    </button>
                    <button @click="page++; loadConversations()" :disabled="page * limit >= totalConversations"
                            class="px-2 py-1 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded disabled:opacity-50">
                        <span x-html="$icon('chevron-right', 'w-4 h-4')"></span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Conversation Detail (Right Panel) -->
    <div class="flex-1 flex flex-col bg-white rounded-lg shadow-md dark:bg-gray-800 overflow-hidden">
        <!-- No conversation selected -->
        <template x-if="!selectedConversationId">
            <div class="flex-1 flex items-center justify-center text-gray-500 dark:text-gray-400">
                <div class="text-center">
                    <span x-html="$icon('chat-bubble-left-right', 'w-16 h-16 mx-auto mb-4 text-gray-300')"></span>
                    <p class="font-medium">Select a conversation</p>
                    <p class="text-sm mt-1">Or start a new one</p>
                </div>
            </div>
        </template>

        <!-- Conversation loaded -->
        <template x-if="selectedConversationId && selectedConversation">
            <div class="flex flex-col h-full">
                <!-- Header -->
                <div class="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100" x-text="selectedConversation.subject"></h3>
                        <div class="flex items-center gap-2 mt-1">
                            <span class="text-sm text-gray-500 dark:text-gray-400">
                                with <span class="font-medium" x-text="getOtherParticipantName()"></span>
                            </span>
                            <span x-show="selectedConversation.store_name"
                                  class="text-xs text-gray-400">
                                (<span x-text="selectedConversation.store_name"></span>)
                            </span>
                        </div>
                    </div>
                    <div class="flex items-center gap-2">
                        <template x-if="!selectedConversation.is_closed">
                            <button @click="showCloseConversationConfirm = true"
                                    class="px-3 py-1.5 text-sm font-medium text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600">
                                Close
                            </button>
                        </template>
                        <template x-if="selectedConversation.is_closed">
                            <button @click="reopenConversation()"
                                    class="px-3 py-1.5 text-sm font-medium text-purple-600 bg-purple-100 rounded-lg hover:bg-purple-200 dark:bg-purple-900 dark:text-purple-300">
                                Reopen
                            </button>
                        </template>
                    </div>
                </div>

                <!-- Messages -->
                <div class="flex-1 overflow-y-auto p-4 space-y-4" x-ref="messagesContainer">
                    <template x-if="loadingMessages">
                        <div class="flex items-center justify-center py-8">
                            <span x-html="$icon('spinner', 'w-6 h-6 animate-spin text-purple-500')"></span>
                        </div>
                    </template>

                    <template x-for="msg in selectedConversation.messages" :key="msg.id">
                        <div class="flex"
                             :class="msg.sender_type === 'admin' ? 'justify-end' : 'justify-start'">
                            <!-- System message -->
                            <template x-if="msg.is_system_message">
                                <div class="text-center w-full py-2">
                                    <span class="px-3 py-1 text-xs text-gray-500 bg-gray-100 rounded-full dark:bg-gray-700 dark:text-gray-400"
                                          x-text="msg.content"></span>
                                </div>
                            </template>

                            <!-- Regular message -->
                            <template x-if="!msg.is_system_message">
                                <div class="max-w-[70%]">
                                    <div class="rounded-lg px-4 py-2"
                                         :class="msg.sender_type === 'admin'
                                             ? 'bg-purple-600 text-white'
                                             : 'bg-gray-100 text-gray-900 dark:bg-gray-700 dark:text-gray-100'">
                                        <p class="text-sm whitespace-pre-wrap" x-text="msg.content"></p>

                                        <!-- Attachments -->
                                        <template x-if="msg.attachments && msg.attachments.length > 0">
                                            <div class="mt-2 space-y-1">
                                                <template x-for="att in msg.attachments" :key="att.id">
                                                    <a :href="att.download_url"
                                                       target="_blank"
                                                       class="flex items-center gap-2 text-xs underline"
                                                       :class="msg.sender_type === 'admin' ? 'text-purple-200 hover:text-white' : 'text-purple-600 hover:text-purple-800 dark:text-purple-400'">
                                                        <span x-html="att.is_image ? $icon('photo', 'w-4 h-4') : $icon('paper-clip', 'w-4 h-4')"></span>
                                                        <span x-text="att.original_filename"></span>
                                                    </a>
                                                </template>
                                            </div>
                                        </template>
                                    </div>
                                    <div class="flex items-center gap-2 mt-1 px-1"
                                         :class="msg.sender_type === 'admin' ? 'justify-end' : 'justify-start'">
                                        <span class="text-xs text-gray-400" x-text="msg.sender_name || 'Unknown'"></span>
                                        <span class="text-xs text-gray-400" x-text="formatTime(msg.created_at)"></span>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </template>
                </div>

                <!-- Reply Form -->
                <template x-if="!selectedConversation.is_closed">
                    <div class="border-t border-gray-200 dark:border-gray-700 p-4">
                        <form @submit.prevent="sendMessage()" class="flex gap-3">
                            <div class="flex-1">
                                <textarea
                                    x-model="replyContent"
                                    @keydown.enter.meta="sendMessage()"
                                    @keydown.enter.ctrl="sendMessage()"
                                    rows="2"
                                    placeholder="Type your message... (Cmd/Ctrl+Enter to send)"
                                    class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300 resize-none"
                                ></textarea>
                                <div class="flex items-center justify-between mt-2">
                                    <label class="flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400 cursor-pointer hover:text-gray-700 dark:hover:text-gray-300">
                                        <input type="file" multiple @change="handleFileSelect" class="hidden" x-ref="fileInput">
                                        <span x-html="$icon('paper-clip', 'w-5 h-5')"></span>
                                        <span>Attach files</span>
                                    </label>
                                    <template x-if="attachedFiles.length > 0">
                                        <div class="flex items-center gap-2 text-sm text-gray-500">
                                            <span x-text="attachedFiles.length + ' file(s)'"></span>
                                            <button type="button" @click="attachedFiles = []" class="text-red-500 hover:text-red-700">
                                                <span x-html="$icon('x-mark', 'w-4 h-4')"></span>
                                            </button>
                                        </div>
                                    </template>
                                </div>
                            </div>
                            <button type="submit"
                                    :disabled="!replyContent.trim() && attachedFiles.length === 0 || sendingMessage"
                                    class="px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed self-end">
                                <span x-show="!sendingMessage" x-html="$icon('paper-airplane', 'w-5 h-5')"></span>
                                <span x-show="sendingMessage" x-html="$icon('spinner', 'w-5 h-5 animate-spin')"></span>
                            </button>
                        </form>
                    </div>
                </template>

                <!-- Closed message -->
                <template x-if="selectedConversation.is_closed">
                    <div class="border-t border-gray-200 dark:border-gray-700 p-4 text-center text-gray-500 dark:text-gray-400">
                        <p class="text-sm">This conversation is closed. Reopen it to send messages.</p>
                    </div>
                </template>
            </div>
        </template>
    </div>
</div>

<!-- Compose Modal -->
{% call form_modal('composeModal', 'New Conversation', show_var='showComposeModal', submit_action='createConversation()', submit_text='Start Conversation', loading_var='creatingConversation', loading_text='Creating...') %}
    <!-- Recipient Type -->
    <div class="space-y-4">
        <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Send to</label>
            <select
                x-model="compose.recipientType"
                @change="compose.recipientId = null; loadRecipients()"
                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
            >
                <option value="">Select type...</option>
                <option value="store">Store</option>
                <option value="customer">Customer</option>
            </select>
        </div>

        <!-- Recipient -->
        <div x-show="compose.recipientType">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Recipient</label>
            <select
                x-model="compose.recipientId"
                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
            >
                <option value="">Select recipient...</option>
                <template x-for="r in recipients" :key="r.id">
                    <option :value="r.id" x-text="r.name + (r.store_name ? ' (' + r.store_name + ')' : '') + ' - ' + (r.email || '')"></option>
                </template>
            </select>
        </div>

        <!-- Subject -->
        <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Subject</label>
            <input
                type="text"
                x-model="compose.subject"
                placeholder="What is this about?"
                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
            >
        </div>

        <!-- Message -->
        <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Message</label>
            <textarea
                x-model="compose.message"
                rows="4"
                placeholder="Type your message..."
                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300 resize-none"
            ></textarea>
        </div>
    </div>
{% endcall %}

<!-- Close Conversation Confirm Modal -->
{{ confirm_modal('closeConversationConfirm', 'Close Conversation', 'Are you sure you want to close this conversation? You can reopen it later if needed.', 'closeConversation()', 'showCloseConversationConfirm', 'Close Conversation', 'Cancel', 'warning') }}
{% endblock %}

{% block extra_scripts %}
<script defer src="{{ url_for('messaging_static', path='admin/js/messages.js') }}"></script>
{% endblock %}
