<template>
  <div class="space-y-4">
    <!-- Loading State -->
    <div v-if="state.loading.page" class="flex items-center justify-center py-8">
      <Icon icon="eos-icons:loading" class="w-8 h-8 text-blue-600" />
      <span class="ml-2 text-gray-600">{{ $t('Loading content types...') }}</span>
    </div>

    <!-- Content Types Selection -->
    <div v-else class="settings-row border-b border-gray-100 py-4">
      <div class="settings-label">
        <FormLabel
          :title="$t('Content Types')"
          :help="$t('Select which WordPress content types to include in your knowledge base')"
        />
      </div>
      <div class="settings-control">
        <div class="space-y-3 w-full">
          <label
            v-for="postType in availablePostTypes"
            :key="postType.name"
            class="flex items-center p-3 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer transition-colors"
            :class="{ 'border-blue-500 bg-blue-50': form.selected_post_types.includes(postType.name) }"
          >
            <input
              type="checkbox"
              :value="postType.name"
              v-model="form.selected_post_types"
              class="rounded border-gray-300 text-blue-600 focus:ring-blue-500 mr-3"
            />
            <div class="flex-1">
              <div class="flex items-center">
                <Icon :icon="getPostTypeIcon(postType.name)" class="w-4 h-4 mr-2 text-gray-500" />
                <span class="font-medium text-gray-900">{{ postType.label }}</span>
                <span class="ml-2 text-sm text-gray-500">({{ postType.count || 0 }})</span>
              </div>
              <p v-if="postType.description" class="text-sm text-gray-600 mt-1">{{ postType.description }}</p>
            </div>
          </label>
        </div>
      </div>
    </div>


    <!-- Index Management -->
    <div class="settings-row border-b border-gray-100 py-4">
      <div class="settings-label">
        <FormLabel
          :title="$t('Index Management')"
          :help="$t('Rebuild or clear the content index as needed')"
        />
      </div>
      <div class="settings-control">
        <div class="w-full">
          <!-- Index Statistics -->
          <div v-if="indexStats.total_count > 0" class="mb-4 p-3 bg-gray-50 rounded-lg">
            <div class="flex items-center justify-between text-sm">
              <div class="flex items-center gap-4">
                <div class="flex items-center gap-2">
                  <Icon icon="material-symbols:database-outline" class="w-4 h-4 text-blue-500" />
                  <span class="font-medium text-gray-700">{{ $t('Total Items:') }}</span>
                  <span class="text-gray-900">{{ indexStats.total_count }}</span>
                </div>
                <div v-if="indexStats.last_indexed_at" class="flex items-center gap-2">
                  <Icon icon="material-symbols:schedule-outline" class="w-4 h-4 text-green-500" />
                  <span class="font-medium text-gray-700">{{ $t('Last Updated:') }}</span>
                  <span class="text-gray-900">{{ formatDate(indexStats.last_indexed_at) }}</span>
                </div>
              </div>
              <div class="flex items-center gap-1">
                <Icon icon="material-symbols:check-circle-outline" class="w-4 h-4 text-green-500" />
                <span class="text-xs text-green-600 font-medium">{{ $t('Active') }}</span>
              </div>
            </div>
          </div>

          <!-- No Index State -->
          <div v-else class="mb-4 p-3 bg-yellow-50 rounded-lg border border-yellow-200">
            <div class="flex items-center gap-2 text-sm">
              <Icon icon="material-symbols:info-outline" class="w-4 h-4 text-yellow-600" />
              <span class="text-yellow-800">{{ $t('No content indexed yet. Click "Rebuild Index" to get started.') }}</span>
            </div>
          </div>

          <!-- Action Buttons -->
          <div class="flex items-center justify-end gap-3">
            <BaseButton
              variant="danger"
              :loading="state.loading.clearing"
              :disabled="state.loading.clearing || state.loading.rebuilding || indexStats.total_count === 0"
              @click="clearIndex"
            >
              {{ $t('Clear Index') }}
            </BaseButton>
            <BaseButton
              variant="primary"
              :loading="state.loading.rebuilding"
              :disabled="state.loading.rebuilding || state.loading.clearing"
              @click="rebuildIndex"
            >
              {{ $t('Rebuild Index') }}
            </BaseButton>
          </div>
        </div>
      </div>
    </div>

    <!-- Automatic Update Features - Upcoming -->
    <div class="settings-row border-b border-gray-100 py-4 opacity-60">
      <div class="settings-label">
          <FormLabel
            :title="$t('Automatic Update Index')"
            :help="$t('Automatically update the content index when posts are modified')"
          />
      </div>
      <div class="settings-control">
        <div class="flex items-center gap-3">
          <button
            type="button"
            disabled
            :title="$t('Upcoming')"
            class="relative inline-flex h-6 w-11 items-center rounded-full bg-gray-200 cursor-not-allowed"
          >
            <span class="inline-block h-4 w-4 transform rounded-full bg-white translate-x-1" />
          </button>
          <span class="text-sm text-gray-500">{{ $t('Toggle automatic updates') }}</span>
        </div>
      </div>
    </div>

    <!-- Auto Update Schedule - Upcoming -->
    <div class="settings-row border-b border-gray-100 py-4 opacity-60">
      <div class="settings-label">
          <FormLabel
            :title="$t('Auto Update Schedule')"
            :help="$t('Set how frequently the content index should be automatically updated')"
          />
      </div>
      <div class="settings-control">
        <select
          disabled
          :title="$t('Upcoming')"
          class="block w-48 px-3 py-2 border border-gray-300 rounded-md shadow-sm bg-gray-50 text-gray-500 cursor-not-allowed"
        >
          <option>{{ $t('Every 15 minutes') }}</option>
          <option>{{ $t('Every 30 minutes') }}</option>
          <option>{{ $t('Every hour') }}</option>
          <option>{{ $t('Every 6 hours') }}</option>
          <option>{{ $t('Daily') }}</option>
        </select>
      </div>
    </div>
    </div>

    <!-- Actions -->
    <div class="flex items-center justify-end pt-2">
      <BaseButton
        variant="primary"
        :loading="state.loading.saving"
        :disabled="state.loading.saving || state.loading.page"
        @click="saveSettings"
      >
        {{ $t('Save Settings') }}
      </BaseButton>
    </div>





    <!-- Clear Index 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"
    />
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { Icon } from '@iconify/vue'
import FormLabel from '@/Admin/Components/FormLabel.vue'
import BaseButton from '@/Admin/Components/BaseButton.vue'
import DeleteConfirmationModal from '@/Admin/Components/DeleteConfirmationModal.vue'

import { useForm } from '@/Admin/js/composables/useForm.js'
import { useToast } from '@/Admin/js/composables/useToast.js'
import { useDeleteConfirmation } from '@/Admin/js/composables/useDeleteConfirmation.js'
import Http from '@/Admin/js/utils/http.js'

// Reactive state
const state = reactive({
    loading: {
        page: false,
        saving: false,
        rebuilding: false,
        clearing: false
    }
})

// Index statistics
const indexStats = ref({
  total_count: 0,
  last_indexed_at: null,
  indexed_post_types: [],
  indexed_count: 0
})

// Toast notifications
const { showSuccess, showError, showInfo } = useToast()

// Delete confirmation modal
const deleteConfirmation = useDeleteConfirmation()

// Available post types (will be loaded from WordPress)
const availablePostTypes = ref([
  { name: 'post', label: 'Posts', count: 0, description: 'Blog posts and articles' },
  { name: 'page', label: 'Pages', count: 0, description: 'Static pages' },
  { name: 'product', label: 'Products', count: 0, description: 'WooCommerce products' },
  { name: 'faq', label: 'FAQs', count: 0, description: 'Frequently asked questions' },
])

// Form defaults for internal content
const makeDefaults = () => ({
  selected_post_types: ['post', 'page']
})

// Initialize form
const form = useForm(makeDefaults())

// Get post type icon
const getPostTypeIcon = (postType) => {
  const icons = {
    post: 'material-symbols:article-outline',
    page: 'material-symbols:description-outline',
    product: 'material-symbols:shopping-bag-outline',
    faq: 'material-symbols:quiz-outline'
  }
  return icons[postType] || 'material-symbols:insert-drive-file-outline'
}

// Format date for display
const formatDate = (dateString) => {
  if (!dateString) return ''

  const date = new Date(dateString)
  const now = new Date()
  const diffInHours = Math.floor((now - date) / (1000 * 60 * 60))

  if (diffInHours < 1) {
    return 'Just now'
  } else if (diffInHours < 24) {
    return `${diffInHours} hour${diffInHours > 1 ? 's' : ''} ago`
  } else if (diffInHours < 48) {
    return 'Yesterday'
  } else {
    return date.toLocaleDateString()
  }
}

// Load available post types from WordPress
const loadPostTypes = async () => {
  try {
    const response = await Http.get('internal-content-settings/post-types')

    if (response.success) {
      availablePostTypes.value = response.data.post_types
    } else {
      showError('Failed to load post types', response.message || 'Please try again')
    }
  } catch (error) {
    console.error('Failed to load post types:', error)
    showError('Failed to load post types', 'Please check your connection and try again')
  }
}

// Load index statistics
const loadIndexStats = async () => {
  try {
    const response = await Http.get('internal-content-index/status')

    if (response.success) {
      indexStats.value = response.data
    }
  } catch (error) {
    console.error('Error loading index stats:', error)
  }
}

// API calls
const loadSettings = async () => {
  state.loading.page = true
  try {
    const response = await Http.get('internal-content-settings')

    if (response.success) {
      // Update form with data from API
      form.fill({
        selected_post_types: response.data.selected_post_types || ['post', 'page']
      })
    } else {
      showError('Failed to load settings', response.message || 'Please try again')
    }
  } catch (error) {
    console.error('Error loading settings:', error)
    showError('Failed to load settings', 'Please check your connection and try again')
  } finally {
    state.loading.page = false
  }
}

// Actions
const saveSettings = async () => {
  state.loading.saving = true
  try {
    const response = await Http.post('internal-content-settings', {
      selected_post_types: form.selected_post_types
    })

    if (response.success) {
      showSuccess('Settings saved successfully!', 'Internal content settings have been updated')
    } else {
      showError('Failed to save settings', response.message || 'Please try again')
    }
  } catch (error) {
    console.error('Error saving settings:', error)
    showError('Failed to save settings', 'An unexpected error occurred')
  } finally {
    state.loading.saving = false
  }
}



const rebuildIndex = async () => {
  state.loading.rebuilding = true
  try {
    const response = await Http.post('internal-content-index/build', {
      selected_post_types: form.selected_post_types
    })

    if (response.success) {
      showSuccess('Index rebuilt successfully!', response.message)
      // Refresh index stats
      await loadIndexStats()
    } else {
      showError('Failed to rebuild index', response.message || 'Please try again later')
    }
  } catch (error) {
    console.error('Failed to rebuild content index:', error)
    showError('Failed to rebuild index', 'Please check your connection and try again')
  } finally {
    state.loading.rebuilding = false
  }
}

// Clear index
const clearIndex = () => {
  deleteConfirmation.showDeleteConfirmation({
    title: 'Clear Content Index',
    message: 'Are you sure you want to clear the entire content index?',
    details: 'This will permanently remove all indexed content from your knowledge base. You will need to rebuild the index to restore functionality. This action cannot be undone.',
    confirmText: 'Clear Index',
    cancelText: 'Cancel',
    onConfirm: async () => {
      try {
        state.loading.clearing = true
        const response = await Http.post('internal-content-index/clear')

        if (response.success) {
          showSuccess('Index cleared successfully!', response.message)
          // Refresh index stats
          await loadIndexStats()
        } else {
          showError('Failed to clear index', response.message || 'Please try again later')
          throw new Error(response.message || 'Failed to clear index')
        }
      } catch (error) {
        console.error('Failed to clear content index:', error)
        showError('Failed to clear index', 'Please check your connection and try again')
        throw error // Re-throw to keep modal open on error
      } finally {
        state.loading.clearing = false
      }
    }
  })
}

// Load data on mount
onMounted(async () => {
  await Promise.all([
    loadPostTypes(),
    loadSettings(),
    loadIndexStats()
  ])
})
</script>

<style lang="scss" scoped>
/* Settings two-column row layout - matching other settings pages */
.settings-row {
  @apply grid grid-cols-1 md:grid-cols-12 items-center gap-6;
}

.settings-label {
  @apply md:col-span-5 flex flex-col justify-center;
}

.settings-control {
  @apply md:col-span-7 flex items-center;
}

.label-title {
  @apply text-sm md:text-base font-medium text-gray-800;
}

.label-help {
  @apply text-xs text-gray-500 mt-1;
}
</style>
