<template>
  <div>
    <div class="bg-white border border-gray-200 rounded-lg shadow-sm overflow-hidden">
      <!-- Loading State -->
      <template v-if="state.loading">
        <div class="px-6 py-8 text-center text-gray-500">
          {{ $t('Loading saved replies...') }}
        </div>
      </template>

      <template v-else>
        <!-- Search and Filters -->
        <div class="px-4 py-3 border-b border-gray-200 flex items-center gap-3">
          <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="searchReplies"
              :placeholder="$t('Search by question or keywords...')"
              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>

          <!-- Status Filter -->
          <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>

        <!-- Table -->
        <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('Question') }}
                </th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  {{ $t('Match Type') }}
                </th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  {{ $t('Language') }}
                </th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  {{ $t('Hits') }}
                </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="reply in state.replies"
                :key="reply.id"
                class="hover:bg-gray-50 transition-colors duration-150"
              >
                <td class="px-6 py-4">
                  <div class="max-w-md">
                    <div class="text-sm font-medium text-gray-900 truncate">
                      {{ reply.question }}
                    </div>
                    <div class="text-xs text-gray-500 truncate mt-1">
                      {{ truncateAnswer(reply.answer) }}
                    </div>
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span :class="matchTypeBadgeClass(reply.match_type)">
                    {{ reply.match_type }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                  {{ reply.language.toUpperCase() }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                  {{ reply.hit_count }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span :class="[
                    'text-xs px-2 py-1 rounded-full',
                    reply.is_active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'
                  ]">
                    {{ reply.is_active ? $t('Active') : $t('Inactive') }}
                  </span>
                </td>
                <td class="px-6 py-4 text-right">
                  <DropdownMenu placement="bottom-end" @click.stop>
                    <template #default="{ close }">
                      <DropdownMenuItem @click="editReply(reply); close()">
                        <template #icon>
                          <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                  d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                          </svg>
                        </template>
                        {{ $t('Edit') }}
                      </DropdownMenuItem>

                      <DropdownMenuItem @click="toggleStatus(reply); close()">
                        <template #icon>
                          <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                  d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path>
                          </svg>
                        </template>
                        {{ reply.is_active ? $t('Deactivate') : $t('Activate') }}
                      </DropdownMenuItem>

                      <DropdownMenuItem variant="danger" @click="deleteReply(reply); 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>

              <!-- Empty State -->
              <tr v-if="!state.loading && state.replies.length === 0">
                <td colspan="6" class="px-6 py-8 text-center text-gray-500">
                  {{ $t('No saved replies found.') }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- Pagination -->
        <Pagination
          v-if="state.paginate.total > 0"
          :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, onMounted } from 'vue'
import { useRouter } from 'vue-router'
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 { debounce } from '@/Admin/js/utils/helper.js'
import { t } from '@/Admin/js/composables/useI18n.js'

const router = useRouter()

// Reactive state
const state = reactive({
  loading: false,
  replies: [],
  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
const statusOptions = [
  { value: 'all', label: t('All') },
  { value: 'active', label: t('Active') },
  { value: 'inactive', label: t('Inactive') }
]

// Load saved replies from API
const loadReplies = async () => {
  try {
    state.loading = 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/saved-replies', queryParams)

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

// Actions
const editReply = (reply) => {
  router.push({ name: 'EditSavedReply', params: { id: reply.id } })
}

const toggleStatus = async (reply) => {
  try {
    const response = await Http.patch(`admin/saved-replies/${reply.id}/toggle-status`)

    if (response.success) {
      reply.is_active = !reply.is_active
    }
  } catch (error) {
    console.error('Failed to toggle status:', error)
  }
}

const deleteReply = (reply) => {
  deleteConfirmation.showDeleteConfirmation({
    title: t('Delete Saved Reply'),
    message: t('Are you sure you want to delete this saved reply?'),
    details: `"${reply.question.substring(0, 50)}${reply.question.length > 50 ? '...' : ''}"`,
    confirmText: t('Delete'),
    cancelText: t('Cancel'),
    onConfirm: async () => {
      try {
        const response = await Http.delete(`admin/saved-replies/${reply.id}`)

        if (response.success) {
          await loadReplies()
        } else {
          throw new Error(response.message || 'Failed to delete saved reply')
        }
      } catch (error) {
        console.error('Failed to delete saved reply:', error)
        alert('Failed to delete saved reply: ' + error.message)
        throw error
      }
    }
  })
}

const setStatusFilter = (status) => {
  state.filters.status = status
  state.paginate.current_page = 1
  loadReplies()
}

// Helpers
const truncateAnswer = (answer, length = 80) => {
  if (answer.length <= length) return answer
  return answer.substring(0, length) + '...'
}

const matchTypeBadgeClass = (type) => {
  const classes = {
    exact: 'text-xs px-2 py-1 rounded-full bg-blue-100 text-blue-700',
    contains: 'text-xs px-2 py-1 rounded-full bg-purple-100 text-purple-700',
    keyword: 'text-xs px-2 py-1 rounded-full bg-amber-100 text-amber-700'
  }
  return classes[type] || classes.exact
}

// Event handlers
const searchReplies = debounce(loadReplies, 500)

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

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

// Initialize
onMounted(loadReplies)
</script>

