<template>
  <div>
    <!-- Loading State -->
    <div v-if="state.loading" class="flex items-center justify-center py-12">
      <svg class="animate-spin h-8 w-8 text-blue-600" fill="none" viewBox="0 0 24 24">
        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
      </svg>
      <span class="ml-3 text-gray-600">{{ $t('Loading analytics...') }}</span>
    </div>

    <template v-else>
      <!-- Overview Cards -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <!-- Total Replies -->
        <div class="bg-white border border-gray-200 rounded-lg p-5">
          <div class="flex items-center">
            <div class="flex-shrink-0 p-3 bg-blue-100 rounded-lg">
              <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"></path>
              </svg>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">{{ $t('Total Replies') }}</p>
              <p class="text-2xl font-bold text-gray-900">{{ stats.total }}</p>
            </div>
          </div>
        </div>

        <!-- Active Replies -->
        <div class="bg-white border border-gray-200 rounded-lg p-5">
          <div class="flex items-center">
            <div class="flex-shrink-0 p-3 bg-green-100 rounded-lg">
              <svg class="w-6 h-6 text-green-600" 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>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">{{ $t('Active') }}</p>
              <p class="text-2xl font-bold text-gray-900">{{ stats.active }}</p>
            </div>
          </div>
        </div>

        <!-- Total Hits -->
        <div class="bg-white border border-gray-200 rounded-lg p-5">
          <div class="flex items-center">
            <div class="flex-shrink-0 p-3 bg-purple-100 rounded-lg">
              <svg class="w-6 h-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 15l-2 5L9 9l11 4-5 2zm0 0l5 5M7.188 2.239l.777 2.897M5.136 7.965l-2.898-.777M13.95 4.05l-2.122 2.122m-5.657 5.656l-2.12 2.122"></path>
              </svg>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">{{ $t('Total Hits') }}</p>
              <p class="text-2xl font-bold text-gray-900">{{ formatNumber(stats.total_hits) }}</p>
            </div>
          </div>
        </div>

        <!-- Average Hits -->
        <div class="bg-white border border-gray-200 rounded-lg p-5">
          <div class="flex items-center">
            <div class="flex-shrink-0 p-3 bg-amber-100 rounded-lg">
              <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="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
              </svg>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">{{ $t('Avg. Hits') }}</p>
              <p class="text-2xl font-bold text-gray-900">{{ stats.avg_hits.toFixed(1) }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- Two Column Layout -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <!-- Top Performing Replies -->
        <div class="bg-white border border-gray-200 rounded-lg shadow-sm">
          <div class="px-5 py-4 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-800">{{ $t('Top Performing Replies') }}</h3>
          </div>
          <div class="p-5">
            <div v-if="stats.top_performers.length === 0" class="text-center py-6 text-gray-500">
              {{ $t('No data available yet') }}
            </div>
            <div v-else class="space-y-4">
              <div v-for="(reply, index) in stats.top_performers" :key="reply.id" class="flex items-center">
                <div class="flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold"
                  :class="getRankClass(index)">
                  {{ index + 1 }}
                </div>
                <div class="ml-3 flex-1 min-w-0">
                  <p class="text-sm font-medium text-gray-900 truncate">{{ reply.question }}</p>
                  <p class="text-xs text-gray-500">{{ reply.match_type }}</p>
                </div>
                <div class="ml-3 flex-shrink-0">
                  <span class="text-sm font-semibold text-gray-900">{{ reply.hit_count }}</span>
                  <span class="text-xs text-gray-500 ml-1">{{ $t('hits') }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Match Type Distribution -->
        <div class="bg-white border border-gray-200 rounded-lg shadow-sm">
          <div class="px-5 py-4 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-800">{{ $t('Match Type Distribution') }}</h3>
          </div>
          <div class="p-5">
            <div v-if="stats.total === 0" class="text-center py-6 text-gray-500">
              {{ $t('No data available yet') }}
            </div>
            <div v-else class="space-y-4">
              <div v-for="type in matchTypes" :key="type.name" class="space-y-2">
                <div class="flex items-center justify-between">
                  <span class="text-sm font-medium text-gray-700 capitalize">{{ type.name }}</span>
                  <span class="text-sm text-gray-500">{{ type.count }} ({{ type.percentage }}%)</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                  <div class="h-2 rounded-full transition-all duration-500" :class="type.colorClass"
                    :style="{ width: type.percentage + '%' }"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Unused Replies -->
      <div v-if="stats.unused_replies.length > 0" class="bg-white border border-amber-200 rounded-lg shadow-sm">
        <div class="px-5 py-4 border-b border-amber-200 bg-amber-50">
          <div class="flex items-center">
            <svg class="w-5 h-5 text-amber-500 mr-2" 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>
            <h3 class="text-lg font-semibold text-gray-800">
              {{ $t('Unused Replies') }}
              <span class="ml-2 text-sm font-normal text-gray-500">({{ stats.unused_replies.length }} {{ $t('replies with 0 hits') }})</span>
            </h3>
          </div>
          <p class="text-sm text-gray-600 mt-1">{{ $t('Consider reviewing or removing these replies to keep your list clean.') }}</p>
        </div>
        <div class="p-5">
          <div class="space-y-3">
            <div v-for="reply in stats.unused_replies.slice(0, 5)" :key="reply.id"
              class="flex items-center justify-between py-2 border-b border-gray-100 last:border-0">
              <div class="flex-1 min-w-0">
                <p class="text-sm font-medium text-gray-900 truncate">{{ reply.question }}</p>
                <p class="text-xs text-gray-500">
                  <span class="capitalize">{{ reply.match_type }}</span>
                  <span class="mx-1">•</span>
                  {{ $t('Created') }} {{ formatDate(reply.created_at) }}
                </p>
              </div>
              <router-link :to="{ name: 'EditSavedReply', params: { id: reply.id } }"
                class="ml-3 text-sm text-blue-600 hover:text-blue-800">
                {{ $t('Edit') }}
              </router-link>
            </div>
          </div>
          <div v-if="stats.unused_replies.length > 5" class="mt-4 text-center">
            <router-link to="/settings/saved-replies" class="text-sm text-blue-600 hover:text-blue-800">
              {{ $t('View all unused replies') }} →
            </router-link>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

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

const state = reactive({
  loading: false
})

const stats = reactive({
  total: 0,
  active: 0,
  inactive: 0,
  total_hits: 0,
  avg_hits: 0,
  match_type_distribution: {},
  top_performers: [],
  unused_replies: []
})

// Computed match types for chart
const matchTypes = computed(() => {
  const distribution = stats.match_type_distribution || {}
  const total = stats.total || 1

  const colors = {
    exact: 'bg-blue-500',
    contains: 'bg-purple-500',
    keywords: 'bg-amber-500'
  }

  return Object.entries(distribution).map(([name, count]) => ({
    name,
    count,
    percentage: Math.round((count / total) * 100),
    colorClass: colors[name] || 'bg-gray-500'
  }))
})

// Load analytics data
const loadAnalytics = async () => {
  try {
    state.loading = true
    const response = await Http.get('admin/saved-replies/analytics')

    if (response.success) {
      Object.assign(stats, response.data)
    }
  } catch (error) {
    console.error('Failed to load analytics:', error)
  } finally {
    state.loading = false
  }
}

// Helpers
const formatNumber = (num) => {
  if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M'
  if (num >= 1000) return (num / 1000).toFixed(1) + 'K'
  return num.toString()
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const now = new Date()
  const diffDays = Math.floor((now - date) / (1000 * 60 * 60 * 24))

  if (diffDays === 0) return 'today'
  if (diffDays === 1) return 'yesterday'
  if (diffDays < 7) return `${diffDays} days ago`
  if (diffDays < 30) return `${Math.floor(diffDays / 7)} weeks ago`
  if (diffDays < 365) return `${Math.floor(diffDays / 30)} months ago`
  return `${Math.floor(diffDays / 365)} years ago`
}

const getRankClass = (index) => {
  const classes = [
    'bg-yellow-100 text-yellow-800',  // 1st - gold
    'bg-gray-200 text-gray-700',       // 2nd - silver
    'bg-amber-100 text-amber-800',     // 3rd - bronze
    'bg-gray-100 text-gray-600',       // 4th
    'bg-gray-100 text-gray-600'        // 5th
  ]
  return classes[index] || classes[4]
}

// Initialize
onMounted(loadAnalytics)
</script>

