<template>
    <div class="max-w-7xl mx-auto">
        <div class="mb-6 mt-6">
            <h1 class="text-3xl font-bold text-gray-900 m-0">{{ $t('Conversations') }}</h1>
            <p class="text-gray-600 mt-2">{{ $t('Browse and manage all chat conversations.') }}</p>
        </div>

        <div class="bg-white border border-gray-200 rounded-lg shadow-sm overflow-hidden">
            <template v-if="state.loading.page">
                <ConversationSkeleton/>
            </template>
            <template v-else>
                <div class="px-4 py-3 border-b border-gray-200 flex items-center gap-3">
                    <!-- Search Input - Takes remaining space -->
                    <div class="flex-1 relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <svg class="h-4 w-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                      d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                            </svg>
                        </div>
                        <input
                            type="text"
                            v-model="state.filters.search"
                            @input="searchConversations"
                            :placeholder="$t('Search by #ID, First Name, Last Name and Email')"
                            class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm"
                        />
                    </div>

                    <!-- Right side status tabs - Takes only needed space -->
                    <div class="flex items-center flex-shrink-0">
                        <div class="flex bg-gray-100 rounded-lg p-1">
                            <button
                                v-for="status in statusOptions"
                                :key="status.value"
                                @click="setStatusFilter(status.value)"
                                :class="[
                  'px-4 py-2 text-sm font-medium rounded-md transition-all duration-200',
                  state.filters.status === status.value
                    ? 'bg-white text-gray-900 shadow-sm'
                    : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                ]"
                            >
                                {{ status.label }}
                            </button>
                        </div>
                    </div>
                </div>

                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                {{ $t('User') }}
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                {{ $t('Messages') }}
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                {{ $t('Tokens Used') }}
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                {{ $t('Created') }}
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                {{ $t('Updated') }}
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                {{ $t('Status') }}
                            </th>
                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                {{ $t('Actions') }}
                            </th>
                        </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-100">
                        <tr
                            v-for="conversation in (pagedConversations || [])"
                            :key="conversation.id"
                            class="hover:bg-gray-50 cursor-pointer transition-colors duration-150"
                            @click="view(conversation)"
                            role="button"
                            tabindex="0"
                            @keydown.enter="view(conversation)"
                            @keydown.space.prevent="view(conversation)"
                        >
                            <td class="px-6 py-3 whitespace-nowrap">
                                <div class="flex items-center gap-3">
                                    <div
                                        class="w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center text-xs font-medium">
                                        {{ initials(conversation.customer?.name || 'Unknown') }}
                                    </div>
                                    <div class="min-w-0">
                                        <div
                                            class="text-sm font-medium text-gray-900 truncate hover:text-blue-600 transition-colors">
                                            {{ conversation.customer?.name || 'Unknown' }}
                                        </div>
                                        <div class="text-xs text-gray-500 truncate">
                                            {{ conversation.customer?.email || '' }}
                                        </div>
                                        <div class="text-xs text-gray-400">
                                            {{
                                                conversation.user_type === 'authenticated' ? 'WordPress User' : 'Public User'
                                            }}
                                        </div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-3 text-sm text-gray-700">
                                <div class="font-medium">{{ conversation.messages_count || 0 }}</div>
                                <div class="text-xs text-gray-500">{{ conversation.department }}</div>
                            </td>
                            <td class="px-6 py-3 text-sm text-gray-700">
                                <div class="font-medium">{{ conversation.total_tokens || 0 }}</div>
                                <div class="text-xs text-gray-500">tokens</div>
                            </td>
                            <td class="px-6 py-3 text-sm text-gray-500">{{ formatDate(conversation.started_at) }}</td>
                            <td class="px-6 py-3 text-sm text-gray-500">
                                {{ formatDate(conversation.ended_at || conversation.updated_at || conversation.started_at) }}
                            </td>
                            <td class="px-6 py-3">
                  <span
                      :class="['text-xs px-2 py-1 rounded-full', conversation.status==='active'?'bg-green-100 text-green-700':'bg-gray-100 text-gray-700']">
                    {{ conversation.status === 'active' ? $t('Active') : $t('Ended') }}
                  </span>
                            </td>
                            <td class="px-6 py-3 text-right">
                                <DropdownMenu placement="bottom-end" @click.stop>
                                    <template #default="{ close }">
                                        <DropdownMenuItem @click="view(conversation); close()">
                                            <template #icon>
                                                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round"
                                                          stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                                    <path stroke-linecap="round" stroke-linejoin="round"
                                                          stroke-width="2"
                                                          d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                                                </svg>
                                            </template>
                                            {{ $t('View') }}
                                        </DropdownMenuItem>

                                        <DropdownMenuItem variant="danger" @click="remove(conversation); close()">
                                            <template #icon>
                                                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round"
                                                          stroke-width="2"
                                                          d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                                </svg>
                                            </template>
                                            {{ $t('Delete') }}
                                        </DropdownMenuItem>
                                    </template>
                                </DropdownMenu>
                            </td>
                        </tr>
                        <tr v-if="!state.loading.page && (!pagedConversations || pagedConversations.length === 0)">
                            <td colspan="7" class="px-6 py-8 text-center text-gray-500">
                                {{ $t('No conversations found.') }}
                            </td>
                        </tr>
                        <tr v-if="state.loading.page">
                            <td colspan="7" class="px-6 py-8 text-center text-gray-500">
                                {{ $t('Loading conversations...') }}
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <Pagination
                    :current-page="state.paginate.current_page"
                    :total-pages="state.paginate.last_page"
                    :total-items="state.paginate.total"
                    :per-page="state.paginate.per_page"
                    @paginate="handlePaginate"
                    @per-page-change="handlePerPageChange"
                />
            </template>
        </div>

        <!-- 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 } from 'vue'
import { useRouter } from 'vue-router'
import ConversationSkeleton from './Components/ConversationSkeleton.vue'
import DeleteConfirmationModal from '@/Admin/Components/DeleteConfirmationModal.vue'
import Pagination from '@/Admin/Components/Pagination.vue'
import DropdownMenu from '@/Admin/Components/DropdownMenu.vue'
import DropdownMenuItem from '@/Admin/Components/DropdownMenuItem.vue'

import { useDeleteConfirmation } from '@/Admin/js/composables/useDeleteConfirmation.js'
import Http from '@/Admin/js/utils/http.js'
import { formatDate, debounce, initials } from '@/Admin/js/utils/helper.js'
import { t } from '@/Admin/js/composables/useI18n.js'

const router = useRouter()

// Reactive state
const state = reactive({
    loading: {
        page: false,
        conversations: false
    },
    conversations: [],
    paginate: {
        total: 0,
        per_page: 10,
        current_page: 1,
        last_page: 1
    },
    filters: {
        search: '',
        status: 'all'
    }
})

// Delete confirmation modal
const deleteConfirmation = useDeleteConfirmation()

// Status filter options - matching actual conversation statuses
const statusOptions = [
    { value: 'all', label: t('All') },
    { value: 'active', label: t('Active') },
    { value: 'closed', label: t('Closed') }
]

// Computed properties
const pagedConversations = computed(() => state.conversations)

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

        const queryParams = {
            page: state.paginate.current_page,
            per_page: state.paginate.per_page,
            search: state.filters.search || '',
            status: state.filters.status === 'all' ? '' : state.filters.status
        }

        const response = await Http.get('admin/conversations', queryParams)

        if (response.success) {
            state.conversations = response.conversations.conversations
            state.paginate = response.conversations.pagination
        }
    } catch (error) {
        console.error('Failed to load conversations:', error)
    } finally {
        state.loading.page = false
        state.loading.conversations = false
    }
}

// Actions
const view = (conversation) => {
    router.push({ name: 'ConversationDetail', params: { id: conversation.id } })
}

const remove = (conversation) => {
    deleteConfirmation.showDeleteConfirmation({
        title: 'Delete Conversation',
        message: `Are you sure you want to delete the conversation with ${conversation.customer?.name || 'Unknown'}?`,
        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/${conversation.id}`)

                if (response.success) {
                    await loadConversations()
                } 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 on error
            }
        }
    })
}

const setStatusFilter = (status) => {
    state.filters.status = status
    state.paginate.current_page = 1 // Reset to first page when filtering
    loadConversations()
}

// Event handlers
const searchConversations = debounce(loadConversations, 500)

const handlePaginate = ({ page, perPage }) => {
    state.paginate.current_page = page
    state.paginate.per_page = perPage
    loadConversations()
}

const handlePerPageChange = ({ perPage }) => {
    state.paginate.per_page = perPage
    state.paginate.current_page = 1
    loadConversations()
}

// Initialize
onMounted(loadConversations)
</script>



