<template>
    <div class="max-w-7xl mx-auto">

        <template v-if="state.loading.page">
            <ConversationDetailsPageSkeleton/>
        </template>
        <template v-else>

            <div class="mb-6 mt-6">
                <h1 class="text-2xl font-bold text-gray-900 m-0"> {{ $t('Conversation #%s', $route.params.id) }} </h1>
                <p class="text-gray-600 mt-2">{{ $t('Review the full thread and participant details.') }}</p>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Conversation thread -->
                <div class="lg:col-span-2">
                    <div class="bg-white border border-gray-200 rounded-lg shadow-sm overflow-hidden">
                        <div class="px-4 py-3 border-b border-gray-200 flex items-center justify-between">
                            <div class="text-sm text-gray-500">
                            <span v-if="state.conversation">
                              {{ $t('Started %s', formatTime(state.conversation.started_at)) }}
                              <span v-if="state.conversation.ended_at"> • {{
                                      $t('Ended %s', formatTime(state.conversation.ended_at))
                                  }}</span>
                              <span v-else-if="state.messages.length > 0"> • {{
                                      $t('Last message %s', state.messages[state.messages.length - 1].time)
                                  }}</span>
                            </span>
                            </div>
                            <div class="flex items-center gap-2">
                                <span class="text-xs px-2 py-1 rounded-full"
                                      :class="state.status==='open' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'">{{
                                        state.status === 'open' ? $t('Open') : $t('Closed')
                                    }}</span>
                                <div class="relative" @keydown.esc="state.menuOpen=false">
                                    <button type="button" class="p-1.5 rounded hover:bg-gray-100" @click="toggleMenu"
                                            :aria-expanded="state.menuOpen ? 'true' : 'false'" :aria-haspopup="true"
                                            aria-label="More actions">
                                        <AppIcon name="more-2-line" size="sm"/>
                                    </button>
                                    <div v-if="state.menuOpen"
                                         class="absolute right-0 mt-2 w-40 bg-white border border-gray-200 rounded-lg shadow-lg z-10">
                                        <button class="w-full text-left px-3 py-2 hover:bg-gray-50 text-sm"
                                                @click="toggleStatus">
                                            {{
                                                state.status === 'open' ? $t('Close conversation') : $t('Re-open conversation')
                                            }}
                                        </button>
                                        <button class="w-full text-left px-3 py-2 hover:bg-red-50 text-sm text-red-600"
                                                @click="deleteConversation">
                                            {{ $t('Delete conversation') }}
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="p-4 space-y-4 overflow-y-auto" ref="scrollEl" style="max-height: 60vh;">
                            <div
                                v-for="(m, idx) in state.messages"
                                :key="m.id"
                                class="flex items-end gap-2 sm:gap-3"
                                :class="(m.sender==='user') ? 'justify-start' : 'justify-end'"
                            >
                                <!-- Avatar bottom-aligned -->
                                <div v-if="m.sender==='agent' || m.sender==='ai'"
                                     class="w-8 h-8 rounded-full flex items-center justify-center text-[10px] font-semibold select-none self-end order-2"
                                     :class="m.sender==='ai' ? 'bg-violet-100 text-violet-700' : 'bg-blue-100 text-blue-700'">
                                    {{ m.sender === 'ai' ? 'AI' : 'A' }}
                                </div>
                                <div v-else
                                     class="w-8 h-8 rounded-full bg-gray-200 text-gray-700 flex items-center justify-center text-[10px] font-semibold select-none self-end">
                                    {{ initials(state.user.name) }}
                                </div>

                                <!-- Bubble -->
                                <div :class="['max-w-[75%] flex-1', (m.sender==='user') ? '' : 'order-1']">
                                    <div :class="[
                  'group relative px-4 py-3 rounded-2xl text-sm shadow-sm',
                  m.sender==='user' ? 'bg-primary-50 text-gray-900' : 'bg-white border border-gray-200'
                ]"
                                         :style="m.sender==='ai' ? 'box-shadow: inset 0 0 0 1px rgba(124,58,237,0.15)' : ''">

                                        <div class="whitespace-pre-wrap leading-relaxed">{{ m.text }}</div>

                                    </div>
                                    <div class="text-[11px] text-gray-500 mt-1"
                                         :class="(m.sender==='user') ? 'text-left' : 'text-right'">{{ m.time }}
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Reply Composer -->
                        <div class="px-4 py-3 border-t border-gray-200 bg-white">
                            <div class="flex items-end gap-3">

                                <div class="flex-1">
                                    <div
                                        class="border border-gray-300 rounded-lg overflow-hidden bg-white focus-within:ring-2 focus-within:ring-primary-500">
                                        <div class="px-3 pt-2">
                    <textarea
                        ref="composerEl"
                        v-model="state.draft"
                        :placeholder="$t('Write a reply...')"
                        rows="1"
                        class="form-textarea w-full resize-none border-0 p-0 focus:ring-0"
                        style="min-height: 42px; max-height: 200px;"
                        @input="autoResize"
                        @keydown.enter.exact.prevent
                        @keydown.meta.enter.prevent="trySend"
                        @keydown.ctrl.enter.prevent="trySend"
                    />
                                        </div>
                                        <div
                                            class="px-2 py-1.5 flex items-center justify-between border-t border-gray-200 bg-gray-50">
                                            <div class="flex items-center">
                                                <label class="inline-flex items-center gap-2 text-xs text-gray-600">
                                                    <input type="checkbox" v-model="state.resolve" class="form-checkbox">
                                                    {{ $t('Resolve after send') }}
                                                </label>
                                            </div>
                                            <div class="flex items-center">
                                                <BaseButton variant="primary" :disabled="!canSend" @click="sendReply">
                                                    <AppIcon name="send-plane-2-fill" size="sm" class="mr-1"/>
                                                    {{ $t('Send') }}
                                                </BaseButton>
                                            </div>
                                        </div>
                                    </div>
                                    <p class="mt-1 text-xs text-gray-400">{{
                                            $t('Press Enter to add a new line. Press %s+Enter to send.', isMac ? '⌘' : 'Ctrl')
                                        }}</p>
                                </div>
                            </div>
                        </div>

                        <div class="px-4 py-3 border-t border-gray-200 flex items-center justify-end">
                            <button class="btn" @click="goBack">{{ $t('Back to list') }}</button>
                        </div>
                    </div>
                </div>

                <!-- Sidebar -->
                <aside class="lg:col-span-1">
                    <div class="bg-white border border-gray-200 rounded-lg shadow-sm overflow-hidden">
                        <div class="px-4 py-3 border-b border-gray-200">
                            <h3 class="text-lg font-semibold text-gray-800 m-0">{{ $t('Customer') }}</h3>
                        </div>
                        <div class="p-4 space-y-4">
                            <div v-if="!state.loading.page" class="flex items-center gap-3">
                                <div class="w-10 h-10 rounded-full flex items-center justify-center text-sm font-medium"
                                     :class="state.user.name === 'Anonymous Customer' ? 'bg-orange-100 text-orange-700' : 'bg-gray-100 text-gray-700'">
                                    {{ initials(state.user.name) }}
                                </div>
                                <div>
                                    <div class="text-sm font-medium text-gray-900">
                                        {{ state.user.name }}
                                        <span v-if="state.user.name === 'Anonymous Customer'"
                                              class="text-xs text-orange-600 ml-1">(No customer data)</span>
                                    </div>
                                    <div class="text-xs text-gray-500">{{ state.user.email }}</div>
                                </div>
                            </div>

                            <!-- Loading state for sidebar -->
                            <div v-else class="flex items-center gap-3">
                                <div class="w-10 h-10 rounded-full bg-gray-200 animate-pulse"></div>
                                <div>
                                    <div class="h-4 w-24 bg-gray-200 rounded animate-pulse mb-1"></div>
                                    <div class="h-3 w-32 bg-gray-200 rounded animate-pulse"></div>
                                </div>
                            </div>

                            <div v-if="!state.loading.page">
                                <div class="text-xs uppercase text-gray-500 mb-1">{{ $t('First message') }}</div>
                                <div class="text-sm text-gray-700">{{ firstMessage }}</div>
                            </div>

                            <!-- Loading state for first message -->
                            <div v-else>
                                <div class="text-xs uppercase text-gray-500 mb-1">{{ $t('First message') }}</div>
                                <div class="h-4 w-full bg-gray-200 rounded animate-pulse"></div>
                            </div>

                            <div v-if="!state.loading.page">
                                <div class="text-xs uppercase text-gray-500 mb-1">{{ $t('Meta') }}</div>
                                <div class="text-sm text-gray-700">
                                    <div>{{ $t('ID: %s', $route.params.id) }}</div>
                                    <div>{{ $t('Status: %s', state.status === 'open' ? $t('Open') : $t('Closed')) }}</div>
                                </div>
                            </div>

                            <!-- Loading state for meta -->
                            <div v-else>
                                <div class="text-xs uppercase text-gray-500 mb-1">{{ $t('Meta') }}</div>
                                <div class="text-sm text-gray-700 space-y-1">
                                    <div class="h-4 w-20 bg-gray-200 rounded animate-pulse"></div>
                                    <div class="h-4 w-24 bg-gray-200 rounded animate-pulse"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </aside>
            </div>
        </template>

        <!-- Delete Confirmation Modal -->
        <DeleteConfirmationModal
            v-model="deleteConfirmation.isVisible.value"
            :title="deleteConfirmation.modalConfig.value.title"
            :message="deleteConfirmation.modalConfig.value.message"
            :details="deleteConfirmation.modalConfig.value.details"
            :confirm-text="deleteConfirmation.modalConfig.value.confirmText"
            :cancel-text="deleteConfirmation.modalConfig.value.cancelText"
            :loading="deleteConfirmation.isLoading.value"
            @confirm="deleteConfirmation.handleConfirm"
            @cancel="deleteConfirmation.handleCancel"
        />
    </div>

</template>

<script setup>
import { reactive, computed, onMounted, nextTick, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import ConversationDetailsPageSkeleton from './Components/ConversationDetailsPageSkeleton.vue'
import DeleteConfirmationModal from '@/Admin/Components/DeleteConfirmationModal.vue'
import AppIcon from '@/Admin/Components/Icon.vue'
import BaseButton from '@/Admin/Components/BaseButton.vue'

import { useDeleteConfirmation } from '@/Admin/js/composables/useDeleteConfirmation.js'
import Http from '@/Admin/js/utils/http.js'
import { formatTime, initials } from '@/Admin/js/utils/helper.js'

const router = useRouter()
const route = useRoute()

// Delete confirmation modal
const deleteConfirmation = useDeleteConfirmation()

// Reactive state
const state = reactive({
    loading: {
        page: true,
        conversation: true,
        sending: false
    },
    // UI state
    menuOpen: false,
    // Form state
    draft: '',
    resolve: false,
    // API data
    conversation: null,
    messages: [],
    user: { name: '', email: '' },
    status: 'open'
})

const isMac = navigator.platform.toLowerCase().includes('mac')
const composerEl = ref(null)

// Computed properties
const firstMessage = computed(() => state.messages[0]?.text || '')
const canSend = computed(() => state.draft.trim().length > 0)

// API calls
const loadConversation = async () => {
    try {
        state.loading.page = true
        state.loading.conversation = true

        const response = await Http.get(`admin/conversations/${route.params.id}`)

        if (response.success) {
            state.conversation = response.conversation
            state.messages = response.conversation.messages

            state.user = {
                name: response.conversation.customer.name,
                email: response.conversation.customer.email,
                id: response.conversation.customer.id,
                user_type: response.conversation.customer.user_id ? 'user' : 'public'
            }

            state.status = response.conversation.ended_at ? 'closed' : 'open'

            state.messages = state.messages.map(msg => ({
                id: msg.id,
                sender: msg.sender_type === 'customer' ? 'user' : (msg.sender_type === 'ai' ? 'ai' : 'agent'),
                text: msg.message,
                time: formatTime(msg.created_at)
            }))
        }
    } catch (error) {
        console.error('Failed to load conversation:', error)
    } finally {
        state.loading.page = false
        state.loading.conversation = false
    }
}

// Actions
const autoResize = () => {
    const el = composerEl.value
    if (!el) return
    // textarea is the first child in the container
    const ta = el
    ta.style.height = 'auto'
    ta.style.height = Math.min(ta.scrollHeight, 200) + 'px'
}

const trySend = () => {
    if (canSend.value) sendReply()
}

const toggleMenu = () => {
    state.menuOpen = !state.menuOpen
}

const toggleStatus = async () => {
    try {
        const response = await Http.patch(`admin/conversations/${route.params.id}/status`, {
            status: state.status === 'open' ? 'closed' : 'open'
        })

        if (response.success) {
            await loadConversation()
        }
    } catch (error) {
        console.error('Failed to toggle status:', error)
    }
}

const deleteConversation = () => {
    const conversationId = route.params.id
    const customerName = state.user?.name || 'this conversation'

    deleteConfirmation.showDeleteConfirmation({
        title: 'Delete Conversation',
        message: `Are you sure you want to delete the conversation with ${customerName}?`,
        details: 'This action cannot be undone. All messages in this conversation will be permanently deleted.',
        confirmText: 'Delete Conversation',
        cancelText: 'Cancel',
        onConfirm: async () => {
            try {
                const response = await Http.delete(`admin/conversations/${conversationId}`)

                if (response.success) {
                    // Navigate back to conversations list
                    router.push({ name: 'Conversations' })
                } else {
                    console.error('Failed to delete conversation:', response.message)
                    throw new Error(response.message || 'Failed to delete conversation')
                }
            } catch (error) {
                console.error('Failed to delete conversation:', error)
                // Show error message (you could add a notification system here)
                alert('Failed to delete conversation: ' + error.message)
                throw error // Re-throw to keep modal open
            }
        }
    })

    // Close the dropdown menu
    state.menuOpen = false
}

const sendReply = async () => {
    if (!canSend.value) return

    try {
        state.loading.sending = true

        const messageText = state.draft.trim()
        const conversationId = route.params.id
        const shouldResolve = state.resolve

        // Call API to send reply
        const result = await Http.post(`admin/conversations/${conversationId}/reply`, {
            message: messageText,
            resolve: shouldResolve
        })

        if (result.success) {
            // Clear the draft
            state.draft = ''
            await loadConversation()
            nextTick(() => autoResize())
        } else {
            await loadConversation()
        }
    } catch (error) {
        console.error('Failed to send reply:', error)
    } finally {
        state.loading.sending = false
    }
}

const goBack = () => {
    router.push({ name: 'Conversations' })
}

// Event handlers
const handleClickOutside = (e) => {
    const menu = e.target.closest('[aria-haspopup]')
    if (!menu) state.menuOpen = false
}

document.addEventListener('click', handleClickOutside)

// Initialize
onMounted(async () => {
    await loadConversation()
    nextTick(() => autoResize())
})
</script>

