<template>
  <div class="bg-white border border-gray-200 rounded-lg shadow-sm overflow-hidden">
    <!-- Header Section -->
    <div class="bg-gradient-to-r from-indigo-50 to-purple-50 border-b border-indigo-200 p-6">
      <div class="flex items-start justify-between">
        <div>
          <h3 class="text-lg font-semibold text-gray-800 flex items-center">
            <svg class="w-5 h-5 mr-2 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path>
            </svg>
            {{ $t('Semantic Matching') }}
            <span class="ml-2 text-xs px-2 py-0.5 bg-indigo-100 text-indigo-700 rounded-full">AI-Powered</span>
          </h3>
          <p class="text-sm text-gray-600 mt-1">
            {{ $t('Use AI embeddings to find semantically similar questions, even when wording differs.') }}
          </p>
        </div>
        <div class="flex items-center">
          <label class="relative inline-flex items-center cursor-pointer">
            <input type="checkbox" v-model="settings.enabled" @change="onToggle" class="sr-only peer" :disabled="state.loading">
            <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
            <span class="ml-3 text-sm font-medium" :class="settings.enabled ? 'text-indigo-700' : 'text-gray-500'">
              {{ settings.enabled ? $t('Enabled') : $t('Disabled') }}
            </span>
          </label>
        </div>
      </div>
    </div>

    <!-- Settings Panel (shown when enabled) -->
    <transition name="slide">
      <div v-if="settings.enabled" class="p-6">
        <!-- Threshold Slider -->
        <div class="mb-6">
          <div class="flex items-center justify-between mb-2">
            <label class="text-sm font-medium text-gray-700">{{ $t('Similarity Threshold') }}</label>
            <span class="text-sm font-semibold text-indigo-600">{{ (settings.threshold * 100).toFixed(0) }}%</span>
          </div>
          <input type="range" v-model.number="settings.threshold" min="0.5" max="0.95" step="0.05"
            class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-indigo-600"
            @change="onThresholdChange" />
          <div class="flex justify-between text-xs text-gray-500 mt-1">
            <span>{{ $t('More matches (50%)') }}</span>
            <span>{{ $t('Stricter (95%)') }}</span>
          </div>
        </div>

        <!-- Embedding Status -->
        <div class="bg-white rounded-lg p-4 border border-gray-200">
          <h4 class="text-sm font-medium text-gray-700 mb-3">{{ $t('Embedding Status') }}</h4>
          <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
            <div class="text-center">
              <div class="text-2xl font-bold text-gray-800">{{ status.total }}</div>
              <div class="text-xs text-gray-500">{{ $t('Total') }}</div>
            </div>
            <div class="text-center">
              <div class="text-2xl font-bold text-green-600">{{ status.with_embeddings }}</div>
              <div class="text-xs text-gray-500">{{ $t('Ready') }}</div>
            </div>
            <div class="text-center">
              <div class="text-2xl font-bold text-amber-600">{{ status.without_embeddings }}</div>
              <div class="text-xs text-gray-500">{{ $t('Pending') }}</div>
            </div>
            <div class="text-center">
              <div class="text-sm font-semibold text-indigo-600 capitalize">{{ status.provider }}</div>
              <div class="text-xs text-gray-500">{{ $t('Provider') }}</div>
            </div>
          </div>

          <!-- Provider Mismatch Warning -->
          <div v-if="status.mismatched > 0" class="mb-4 p-3 bg-amber-50 border border-amber-200 rounded-lg">
            <div class="flex items-start">
              <svg class="w-5 h-5 text-amber-500 mr-2 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
              </svg>
              <div>
                <p class="text-sm font-medium text-amber-800">{{ $t('Provider Mismatch Detected') }}</p>
                <p class="text-xs text-amber-700 mt-1">
                  {{ $t('%s embeddings were created with a different provider. Regenerate all for consistent matching quality.', status.mismatched) }}
                </p>
              </div>
            </div>
          </div>

          <!-- Progress Bar -->
          <div v-if="state.processing" class="mb-4">
            <div class="flex items-center justify-between mb-1">
              <span class="text-sm text-gray-600">{{ state.processingLabel }}</span>
              <span class="text-sm font-medium text-indigo-600">{{ progress.current }}/{{ progress.total }}</span>
            </div>
            <div class="w-full bg-gray-200 rounded-full h-2">
              <div class="bg-indigo-600 h-2 rounded-full transition-all duration-300" :style="{ width: progressPercent + '%' }"></div>
            </div>
          </div>

          <!-- Action Buttons -->
          <div class="flex flex-wrap items-center gap-3">
            <!-- Generate Missing -->
            <button v-if="status.without_embeddings > 0" @click="generateMissing" :disabled="state.processing"
              class="inline-flex items-center px-4 py-2 bg-indigo-600 text-white text-sm font-medium rounded-md hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
              <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
              </svg>
              {{ $t('Generate Missing') }} ({{ status.without_embeddings }})
            </button>

            <!-- Regenerate All -->
            <button v-if="status.with_embeddings > 0" @click="showRegenerateModal = true" :disabled="state.processing"
              class="inline-flex items-center px-4 py-2 bg-white text-gray-700 text-sm font-medium rounded-md border border-gray-300 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
              <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
              </svg>
              {{ $t('Regenerate All') }}
            </button>

            <!-- Clear All -->
            <button v-if="status.with_embeddings > 0" @click="showClearModal = true" :disabled="state.processing"
              class="inline-flex items-center px-4 py-2 bg-white text-red-600 text-sm font-medium rounded-md border border-red-200 hover:bg-red-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
              <svg class="w-4 h-4 mr-2" 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>
              {{ $t('Clear All') }}
            </button>

            <!-- All Ready Indicator -->
            <div v-if="status.total > 0 && status.without_embeddings === 0 && status.mismatched === 0" class="flex items-center text-green-600">
              <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
              </svg>
              <span class="text-sm font-medium">{{ $t('All embeddings ready') }}</span>
            </div>
          </div>
        </div>
      </div>
    </transition>

    <!-- Regenerate Confirmation Modal -->
    <Teleport to="body">
      <div v-if="showRegenerateModal" class="fixed inset-0 z-50 overflow-y-auto">
        <div class="flex min-h-full items-center justify-center p-4">
          <div class="fixed inset-0 bg-black/50" @click="showRegenerateModal = false"></div>
          <div class="relative bg-white rounded-lg shadow-xl max-w-md w-full p-6">
            <div class="flex items-center mb-4">
              <div class="w-10 h-10 rounded-full bg-amber-100 flex items-center justify-center mr-3">
                <svg class="w-6 h-6 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                </svg>
              </div>
              <h3 class="text-lg font-semibold text-gray-900">{{ $t('Regenerate All Embeddings?') }}</h3>
            </div>
            <p class="text-sm text-gray-600 mb-4">
              {{ $t('This will regenerate embeddings for all {count} saved replies using the current provider ({provider}).', { count: status.total, provider: status.provider }) }}
            </p>
            <div class="bg-amber-50 border border-amber-200 rounded-lg p-3 mb-4">
              <p class="text-sm text-amber-800 font-medium">{{ $t('This action:') }}</p>
              <ul class="text-sm text-amber-700 mt-1 list-disc list-inside">
                <li>{{ $t('May take several minutes') }}</li>
                <li>{{ $t('Will use API credits') }}</li>
                <li>{{ $t('Cannot be undone') }}</li>
              </ul>
            </div>
            <div class="flex justify-end gap-3">
              <button @click="showRegenerateModal = false" class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50">
                {{ $t('Cancel') }}
              </button>
              <button @click="regenerateAll" class="px-4 py-2 text-sm font-medium text-white bg-indigo-600 rounded-md hover:bg-indigo-700">
                {{ $t('Regenerate All') }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- Clear Confirmation Modal -->
    <Teleport to="body">
      <div v-if="showClearModal" class="fixed inset-0 z-50 overflow-y-auto">
        <div class="flex min-h-full items-center justify-center p-4">
          <div class="fixed inset-0 bg-black/50" @click="showClearModal = false"></div>
          <div class="relative bg-white rounded-lg shadow-xl max-w-md w-full p-6">
            <div class="flex items-center mb-4">
              <div class="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center mr-3">
                <svg class="w-6 h-6 text-red-600" 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>
              </div>
              <h3 class="text-lg font-semibold text-gray-900">{{ $t('Clear All Embeddings?') }}</h3>
            </div>
            <p class="text-sm text-gray-600 mb-4">
              {{ $t('This will remove embeddings from all {count} saved replies. Semantic matching will not work until you generate new embeddings.', { count: status.with_embeddings }) }}
            </p>
            <div class="flex justify-end gap-3">
              <button @click="showClearModal = false" class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50">
                {{ $t('Cancel') }}
              </button>
              <button @click="clearAll" class="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-md hover:bg-red-700">
                {{ $t('Clear All') }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue'
import Http from '@/Admin/js/utils/http.js'
import { useToast } from '@/Admin/js/composables/useToast.js'

const { showSuccess, showError } = useToast()

const showRegenerateModal = ref(false)
const showClearModal = ref(false)

const state = reactive({
  loading: false,
  processing: false,
  processingLabel: ''
})

const settings = reactive({
  enabled: false,
  threshold: 0.75
})

const status = reactive({
  total: 0,
  with_embeddings: 0,
  without_embeddings: 0,
  provider: 'openai',
  provider_stats: {},
  mismatched: 0
})

const progress = reactive({
  current: 0,
  total: 0
})

const progressPercent = computed(() => {
  if (progress.total === 0) return 0
  return Math.round((progress.current / progress.total) * 100)
})

// Load settings and status
const loadSettings = async () => {
  try {
    state.loading = true
    const response = await Http.get('admin/saved-replies/semantic-settings')
    if (response.success) {
      settings.enabled = response.data.enabled ?? false
      settings.threshold = response.data.threshold ?? 0.75
      Object.assign(status, response.data.status || {})
    }
  } catch (error) {
    console.error('Failed to load semantic settings:', error)
  } finally {
    state.loading = false
  }
}

// Toggle semantic matching
const onToggle = async () => {
  try {
    const response = await Http.post('admin/saved-replies/semantic-settings', {
      enabled: settings.enabled,
      threshold: settings.threshold
    })
    if (response.success) {
      showSuccess(settings.enabled ? 'Semantic matching enabled' : 'Semantic matching disabled')
    }
  } catch (error) {
    showError('Failed to update settings')
    settings.enabled = !settings.enabled
  }
}

// Update threshold
const onThresholdChange = async () => {
  try {
    await Http.post('admin/saved-replies/semantic-settings', {
      enabled: settings.enabled,
      threshold: settings.threshold
    })
  } catch (error) {
    showError('Failed to update threshold')
  }
}

// Generate missing embeddings
const generateMissing = async () => {
  try {
    state.processing = true
    state.processingLabel = 'Generating embeddings...'
    progress.current = 0
    progress.total = status.without_embeddings

    const response = await Http.post('admin/saved-replies/generate-embeddings')
    if (response.success) {
      progress.current = progress.total
      showSuccess(response.message || 'Embeddings generated successfully')
      await loadSettings()
    } else {
      showError(response.message || 'Failed to generate embeddings')
    }
  } catch (error) {
    showError('Failed to generate embeddings: ' + (error.message || 'Unknown error'))
  } finally {
    state.processing = false
  }
}

// Regenerate all embeddings
const regenerateAll = async () => {
  showRegenerateModal.value = false
  try {
    state.processing = true
    state.processingLabel = 'Regenerating all embeddings...'
    progress.current = 0
    progress.total = status.total

    const response = await Http.post('admin/saved-replies/regenerate-embeddings')
    if (response.success) {
      progress.current = progress.total
      showSuccess(response.message || 'All embeddings regenerated successfully')
      await loadSettings()
    } else {
      showError(response.message || 'Failed to regenerate embeddings')
    }
  } catch (error) {
    showError('Failed to regenerate embeddings: ' + (error.message || 'Unknown error'))
  } finally {
    state.processing = false
  }
}

// Clear all embeddings
const clearAll = async () => {
  showClearModal.value = false
  try {
    state.processing = true
    state.processingLabel = 'Clearing embeddings...'

    const response = await Http.post('admin/saved-replies/clear-embeddings')
    if (response.success) {
      showSuccess(response.message || 'All embeddings cleared')
      await loadSettings()
    } else {
      showError(response.message || 'Failed to clear embeddings')
    }
  } catch (error) {
    showError('Failed to clear embeddings: ' + (error.message || 'Unknown error'))
  } finally {
    state.processing = false
  }
}

// Initialize
onMounted(loadSettings)
</script>

<style scoped>
.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease;
}

.slide-enter-from,
.slide-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>

