<template>
  <div>
    <!-- Page Header -->
    <div class="mb-8">
      <h1 class="text-2xl font-bold text-white">Szolgáltatók</h1>
      <p class="text-slate-400 mt-1">Szolgáltatók listázása, keresése és moderálása</p>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-2 md:grid-cols-5 gap-4 mb-8">
      <div class="bg-slate-800 rounded-xl border border-slate-700 p-4">
        <p class="text-xs text-slate-400 uppercase tracking-wider">Összes</p>
        <p class="text-2xl font-bold text-white mt-1">{{ stats.total }}</p>
      </div>
      <div class="bg-slate-800 rounded-xl border border-amber-500/30 p-4">
        <p class="text-xs text-slate-400 uppercase tracking-wider">Függőben</p>
        <p class="text-2xl font-bold text-amber-400 mt-1">{{ stats.pending }}</p>
      </div>
      <div class="bg-slate-800 rounded-xl border border-emerald-500/30 p-4">
        <p class="text-xs text-slate-400 uppercase tracking-wider">Jóváhagyott</p>
        <p class="text-2xl font-bold text-emerald-400 mt-1">{{ stats.approved }}</p>
      </div>
      <div class="bg-slate-800 rounded-xl border border-rose-500/30 p-4">
        <p class="text-xs text-slate-400 uppercase tracking-wider">Elutasított</p>
        <p class="text-2xl font-bold text-rose-400 mt-1">{{ stats.rejected }}</p>
      </div>
      <div class="bg-slate-800 rounded-xl border border-purple-500/30 p-4">
        <p class="text-xs text-slate-400 uppercase tracking-wider">Megjelölt</p>
        <p class="text-2xl font-bold text-purple-400 mt-1">{{ stats.flagged }}</p>
      </div>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="flex items-center justify-center py-20">
      <div class="text-slate-400 flex items-center gap-3">
        <svg class="w-5 h-5 animate-spin" 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" />
        </svg>
        <span>Szolgáltatók betöltése...</span>
      </div>
    </div>

    <!-- Error State -->
    <div v-else-if="error" class="bg-rose-500/10 border border-rose-500/30 rounded-xl p-6 mb-8">
      <p class="text-rose-400">Hiba történt a szolgáltatók betöltése közben.</p>
      <button @click="fetchProviders" class="mt-3 text-sm text-rose-300 hover:text-rose-200 underline">Újrapróbálkozás</button>
    </div>

    <template v-else>
      <!-- Filters -->
      <div class="bg-slate-800 rounded-xl border border-slate-700 p-4 mb-6">
        <div class="flex flex-wrap items-center gap-4">
          <!-- Search -->
          <div class="flex-1 min-w-[200px]">
            <input
              v-model="filters.search"
              type="text"
              placeholder="Keresés név alapján..."
              class="w-full px-3 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500 text-sm"
              @input="onSearchInput"
            />
          </div>

          <!-- Status Filter -->
          <select
            v-model="filters.status"
            class="px-3 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500 text-sm"
            @change="fetchProviders"
          >
            <option value="">Minden státusz</option>
            <option value="pending">Függőben</option>
            <option value="approved">Jóváhagyott</option>
            <option value="rejected">Elutasított</option>
            <option value="flagged">Megjelölt</option>
          </select>

          <!-- Source Filter -->
          <select
            v-model="filters.source"
            class="px-3 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500 text-sm"
            @change="fetchProviders"
          >
            <option value="">Minden forrás</option>
            <option value="manual">Kézi</option>
            <option value="ocr">OCR</option>
            <option value="import">Import</option>
          </select>

          <!-- Sort -->
          <select
            v-model="filters.sort_by"
            class="px-3 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500 text-sm"
            @change="fetchProviders"
          >
            <option value="created_at">Létrehozás dátuma</option>
            <option value="name">Név</option>
            <option value="validation_score">Validációs pontszám</option>
          </select>

          <button
            @click="filters.sort_order = filters.sort_order === 'asc' ? 'desc' : 'asc'; fetchProviders()"
            class="px-3 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white hover:bg-slate-600 transition text-sm flex items-center gap-1"
          >
            <svg class="w-4 h-4" :class="filters.sort_order === 'asc' ? 'rotate-180' : ''" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
            </svg>
            {{ filters.sort_order === 'asc' ? 'Növekvő' : 'Csökkenő' }}
          </button>
        </div>
      </div>

      <!-- Providers Table -->
      <div class="bg-slate-800 rounded-xl border border-slate-700 overflow-hidden">
        <table class="w-full">
          <thead>
            <tr class="border-b border-slate-700">
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">ID</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">Név</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">Cím</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">Státusz</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">Forrás</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">Validáció</th>
              <th class="text-left px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">Létrehozva</th>
              <th class="text-right px-6 py-4 text-xs font-medium text-slate-400 uppercase tracking-wider">Műveletek</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-slate-700/50">
            <tr v-for="provider in providers" :key="provider.id" class="hover:bg-slate-700/30 transition">
              <td class="px-6 py-4 text-sm text-slate-400">{{ provider.id }}</td>
              <td class="px-6 py-4">
                <NuxtLink :to="`/providers/${provider.id}`" class="text-sm font-medium text-indigo-400 hover:text-indigo-300 transition">
                  {{ provider.name }}
                </NuxtLink>
              </td>
              <td class="px-6 py-4 text-sm text-slate-300 max-w-[200px] truncate">{{ provider.address || '—' }}</td>
              <td class="px-6 py-4">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium" :class="statusClass(provider.status)">
                  {{ statusLabel(provider.status) }}
                </span>
              </td>
              <td class="px-6 py-4">
                <code class="text-xs font-mono text-slate-400 bg-slate-700/50 px-2 py-0.5 rounded">{{ provider.source }}</code>
              </td>
              <td class="px-6 py-4">
                <div class="flex items-center gap-2">
                  <div class="w-16 h-1.5 bg-slate-700 rounded-full overflow-hidden">
                    <div
                      class="h-full rounded-full transition-all"
                      :class="provider.validation_score >= 50 ? 'bg-emerald-500' : provider.validation_score >= 20 ? 'bg-amber-500' : 'bg-slate-500'"
                      :style="{ width: Math.min(provider.validation_score, 100) + '%' }"
                    />
                  </div>
                  <span class="text-xs text-slate-400">{{ provider.validation_score }}</span>
                </div>
              </td>
              <td class="px-6 py-4 text-sm text-slate-400">{{ formatDate(provider.created_at) }}</td>
              <td class="px-6 py-4 text-right">
                <div class="flex items-center justify-end gap-2">
                  <NuxtLink
                    :to="`/providers/${provider.id}`"
                    class="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-700 transition"
                    title="Részletek"
                  >
                    <svg class="w-4 h-4" 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 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" />
                    </svg>
                  </NuxtLink>
                </div>
              </td>
            </tr>
            <tr v-if="providers.length === 0">
              <td colspan="8" class="px-6 py-12 text-center text-sm text-slate-500">
                Nincs megjeleníthető szolgáltató.
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <div class="flex items-center justify-between mt-6">
        <p class="text-sm text-slate-400">
          {{ providers.length }} találat (összesen: {{ stats.total }})
        </p>
        <div class="flex items-center gap-2">
          <button
            :disabled="filters.skip <= 0"
            @click="filters.skip = Math.max(0, filters.skip - filters.limit); fetchProviders()"
            class="px-3 py-1.5 bg-slate-700 border border-slate-600 rounded-lg text-white disabled:opacity-50 disabled:cursor-not-allowed hover:bg-slate-600 transition text-sm"
          >
            Előző
          </button>
          <span class="text-sm text-slate-400">
            {{ Math.floor(filters.skip / filters.limit) + 1 }}. oldal
          </span>
          <button
            :disabled="providers.length < filters.limit"
            @click="filters.skip += filters.limit; fetchProviders()"
            class="px-3 py-1.5 bg-slate-700 border border-slate-600 rounded-lg text-white disabled:opacity-50 disabled:cursor-not-allowed hover:bg-slate-600 transition text-sm"
          >
            Következő
          </button>
        </div>
      </div>
    </template>

    <!-- Success Toast -->
    <div v-if="toast" class="fixed bottom-6 right-6 z-50 bg-emerald-600 text-white px-4 py-3 rounded-lg shadow-lg text-sm flex items-center gap-2 animate-slide-up">
      <svg class="w-4 h-4 flex-shrink-0" 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" />
      </svg>
      {{ toast }}
    </div>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  middleware: 'auth',
})

const { formatDate } = useFormatter()

interface ProviderListItem {
  id: number
  name: string
  address: string | null
  city: string | null
  category: string | null
  status: string
  source: string
  validation_score: number
  added_by_user_id: number | null
  created_at: string | null
}

interface ProviderStats {
  total: number
  pending: number
  approved: number
  rejected: number
  flagged: number
  total_validations: number
}

const loading = ref(true)
const error = ref(false)
const providers = ref<ProviderListItem[]>([])
const stats = ref<ProviderStats>({
  total: 0,
  pending: 0,
  approved: 0,
  rejected: 0,
  flagged: 0,
  total_validations: 0,
})
const toast = ref('')
let searchTimeout: ReturnType<typeof setTimeout> | null = null

const filters = reactive({
  search: '',
  status: '',
  source: '',
  sort_by: 'created_at',
  sort_order: 'desc',
  skip: 0,
  limit: 50,
})

function getHeaders(): Record<string, string> {
  const tokenCookie = useCookie('access_token')
  const token = tokenCookie.value
  return token ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' } : { 'Content-Type': 'application/json' }
}

function showToast(msg: string) {
  toast.value = msg
  setTimeout(() => { toast.value = '' }, 3000)
}

function statusClass(status: string): string {
  const map: Record<string, string> = {
    pending: 'bg-amber-500/10 text-amber-400',
    approved: 'bg-emerald-500/10 text-emerald-400',
    rejected: 'bg-rose-500/10 text-rose-400',
    flagged: 'bg-purple-500/10 text-purple-400',
  }
  return map[status] || 'bg-slate-500/10 text-slate-400'
}

function statusLabel(status: string): string {
  const map: Record<string, string> = {
    pending: 'Függőben',
    approved: 'Jóváhagyott',
    rejected: 'Elutasított',
    flagged: 'Megjelölt',
  }
  return map[status] || status
}

function onSearchInput() {
  if (searchTimeout) clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    filters.skip = 0
    fetchProviders()
  }, 400)
}

async function fetchStats() {
  try {
    const data = await $fetch<ProviderStats>('/api/v1/admin/providers/stats', { headers: getHeaders() })
    stats.value = data
  } catch (e) {
    console.error('Failed to fetch provider stats:', e)
  }
}

async function fetchProviders() {
  loading.value = true
  error.value = false
  try {
    const params = new URLSearchParams()
    params.append('skip', String(filters.skip))
    params.append('limit', String(filters.limit))
    params.append('sort_by', filters.sort_by)
    params.append('sort_order', filters.sort_order)
    if (filters.status) params.append('status', filters.status)
    if (filters.source) params.append('source', filters.source)
    if (filters.search) params.append('search', filters.search)

    const data = await $fetch<ProviderListItem[]>(`/api/v1/admin/providers?${params.toString()}`, { headers: getHeaders() })
    providers.value = data
  } catch (e) {
    console.error('Failed to fetch providers:', e)
    error.value = true
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchStats()
  fetchProviders()
})
</script>

<style scoped>
.animate-slide-up {
  animation: slideUp 0.3s ease-out;
}
@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(1rem);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
