<script setup>
import { ref, onMounted } from 'vue'
import DashboardLayout from '../layouts/DashboardLayout.vue'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'

const stats = ref(null)
const categories = ref([])
const keys = ref([])
const loading = ref(true)
const searchPattern = ref('*')
const searchLoading = ref(false)
const toast = ref({ show: false, msg: '', type: 'success' })
const keyModal = ref({ show: false, key: '', type: '', ttl: '', value: '' })

function formatTTL(ttl) {
  if (ttl === -1) return '∞'
  if (ttl === -2) return '⚠ expired'
  if (ttl > 86400) return `${Math.floor(ttl/86400)}d ${Math.floor((ttl%86400)/3600)}h`
  if (ttl > 3600) return `${Math.floor(ttl/3600)}h ${Math.floor((ttl%3600)/60)}m`
  if (ttl > 60) return `${Math.floor(ttl/60)}m ${ttl%60}s`
  return ttl + 's'
}
function formatSize(b) {
  if (b < 0) return '—'
  if (b < 1024) return b + ' B'
  if (b < 1048576) return (b/1024).toFixed(1) + ' KB'
  return (b/1048576).toFixed(2) + ' MB'
}
function showToast(msg, type = 'success') {
  toast.value = { show: true, msg, type }
  setTimeout(() => toast.value.show = false, 3000)
}

async function loadStats() {
  loading.value = true
  try {
    const r = await fetch('/api/cache/stats')
    const d = await r.json()
    if (d.error) throw new Error(d.error)
    stats.value = d
    const cats = d.categories || {}
    categories.value = Object.entries(cats)
      .sort((a, b) => b[1].count - a[1].count)
      .map(([name, cat]) => ({ name, ...cat }))
  } catch (e) {
    showToast('❌ ' + e.message, 'error')
  } finally {
    loading.value = false
  }
}

async function searchKeys() {
  searchLoading.value = true
  keys.value = []
  try {
    const r = await fetch(`/api/cache/keys?pattern=${encodeURIComponent(searchPattern.value)}&limit=200`)
    const d = await r.json()
    if (d.error) throw new Error(d.error)
    keys.value = d.keys || []
  } catch (e) {
    showToast('❌ ' + e.message, 'error')
  } finally {
    searchLoading.value = false }
}

async function viewKey(key) {
  keyModal.value = { show: true, key, type: '...', ttl: '...', value: 'Loading...' }
  try {
    const r = await fetch('/api/cache/get?key=' + encodeURIComponent(key))
    const d = await r.json()
    if (d.error) throw new Error(d.error)
    keyModal.value.type = d.type
    keyModal.value.ttl = formatTTL(d.ttl)
    keyModal.value.value = typeof d.value === 'object' ? JSON.stringify(d.value, null, 2) : String(d.value)
  } catch (e) {
    keyModal.value.value = '❌ ' + e.message
  }
}

async function clearCat(prefix) {
  if (!confirm(`🗑️ Clear all "${prefix}:*" keys?`)) return
  const r = await fetch('/api/cache/clear?pattern=' + encodeURIComponent(prefix + ':*'), { method: 'POST' })
  const d = await r.json()
  showToast(`🗑️ Đã xóa ${d.deleted} keys`)
  loadStats()
}

async function clearAll() {
  if (!confirm('💥 FLUSH ALL CACHE?\nSẽ xóa TẤT CẢ cached data!')) return
  if (!confirm('⚠️ Bạn chắc chắn? Không thể undo.')) return
  await fetch('/api/cache/clear-all', { method: 'POST' })
  showToast('💥 All cache flushed!')
  loadStats()
}

onMounted(() => loadStats())
</script>

<template>
  <DashboardLayout>
    <div class="p-8 max-w-5xl space-y-6">

      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight text-foreground">Cache Manager</h1>
          <p class="text-sm text-muted-foreground mt-1">
            {{ stats ? `${stats.total_keys?.toLocaleString()} keys · ${stats.memory_used} · Redis ✓` : 'Connecting to Redis...' }}
          </p>
        </div>
        <div class="flex gap-2">
          <Button variant="outline" size="sm" class="gap-2" @click="loadStats">
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/></svg>
            Refresh
          </Button>
          <Button variant="destructive" size="sm" class="gap-2" @click="clearAll">
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
            Flush All
          </Button>
        </div>
      </div>

      <!-- Stats row -->
      <div v-if="stats" class="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card v-for="(item, i) in [
          { label: 'Total Keys',   value: stats.total_keys?.toLocaleString(),              accent: 'text-primary' },
          { label: 'Memory Used',  value: stats.memory_used,                               accent: 'text-emerald-500' },
          { label: 'Peak Memory',  value: stats.memory_peak,                               accent: 'text-amber-500' },
          { label: 'Resp Hits',    value: stats.in_memory_stats?.resp_hits?.toLocaleString(), accent: 'text-foreground' },
        ]" :key="i" class="border-border">
          <CardContent class="p-5">
            <p :class="['text-2xl font-black tabular-nums', item.accent]">{{ item.value || '—' }}</p>
            <p class="text-xs font-semibold text-muted-foreground uppercase tracking-wider mt-2">{{ item.label }}</p>
          </CardContent>
        </Card>
      </div>

      <Separator />

      <!-- Tabs -->
      <Tabs default-value="categories">
        <TabsList>
          <TabsTrigger value="categories">📦 Categories</TabsTrigger>
          <TabsTrigger value="keys" @click="searchKeys">🔑 Key Search</TabsTrigger>
        </TabsList>

        <!-- Categories Tab -->
        <TabsContent value="categories" class="space-y-3 mt-4">
          <div v-if="loading" class="flex flex-col items-center justify-center py-12 text-muted-foreground">
            <div class="w-5 h-5 border-2 border-primary border-t-transparent animate-spin rounded-full mb-3"></div>
            <p class="text-sm">Loading cache data...</p>
          </div>
          <div v-else-if="!categories.length" class="flex flex-col items-center justify-center py-12 text-muted-foreground border border-dashed border-border rounded-xl">
            <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="opacity-20 mb-2"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5V19A9 3 0 0 0 21 19V5"/><path d="M3 12A9 3 0 0 0 21 12"/></svg>
            <p class="text-sm">Cache trống — chưa có key nào</p>
          </div>
          <div v-else class="grid grid-cols-2 gap-4">
            <Card v-for="cat in categories" :key="cat.name" class="border-border">
              <CardHeader class="pb-2 pt-4 px-4">
                <div class="flex items-center justify-between">
                  <CardTitle class="text-sm font-bold text-foreground">{{ cat.name }}</CardTitle>
                  <Badge class="font-mono">{{ cat.count }}</Badge>
                </div>
              </CardHeader>
              <CardContent class="px-4 pb-3 space-y-0.5">
                <div v-for="k in (cat.keys || []).slice(0, 8)" :key="k.key"
                     class="flex items-center justify-between py-1.5 px-2 rounded-md hover:bg-accent/40 cursor-pointer group transition-colors"
                     @click="viewKey(k.key)">
                  <span class="text-xs font-mono text-foreground/70 truncate flex-1">{{ k.key }}</span>
                  <span :class="['text-[10px] ml-2 shrink-0 font-mono', k.ttl > 0 && k.ttl < 300 ? 'text-destructive font-bold' : 'text-muted-foreground']">
                    {{ formatTTL(k.ttl) }}
                  </span>
                </div>
                <div v-if="cat.count > 8" class="text-xs text-muted-foreground text-center py-1.5">
                  + {{ cat.count - 8 }} keys khác
                </div>
                <Button variant="outline" size="sm" class="w-full mt-3 h-7 text-xs text-destructive hover:bg-destructive/10 border-destructive/20 hover:border-destructive/40"
                        @click="clearCat(cat.name)">
                  Xóa {{ cat.name }}:*
                </Button>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <!-- Keys Tab -->
        <TabsContent value="keys" class="mt-4 space-y-4">
          <div class="flex gap-2">
            <Input v-model="searchPattern" placeholder="Pattern (VD: resp_cache:*)" @keydown.enter="searchKeys" />
            <Button @click="searchKeys" :disabled="searchLoading">
              {{ searchLoading ? '⏳' : '🔍 Scan' }}
            </Button>
          </div>

          <div v-if="!keys.length && !searchLoading" class="text-center py-8 text-gray-400">
            <p class="text-sm">Nhập pattern và nhấn Scan</p>
          </div>

          <Card v-else-if="keys.length">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead class="w-8">#</TableHead>
                  <TableHead>Key</TableHead>
                  <TableHead>Type</TableHead>
                  <TableHead>Size</TableHead>
                  <TableHead>TTL</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                <TableRow v-for="(k, i) in keys" :key="k.key"
                          class="cursor-pointer" @click="viewKey(k.key)">
                  <TableCell class="text-muted-foreground text-xs">{{ i + 1 }}</TableCell>
                  <TableCell class="font-mono text-xs max-w-xs truncate text-foreground/80">{{ k.key }}</TableCell>
                  <TableCell>
                    <Badge variant="secondary" class="text-[10px]">{{ k.type }}</Badge>
                  </TableCell>
                  <TableCell class="text-xs text-muted-foreground">{{ formatSize(k.size) }}</TableCell>
                  <TableCell class="text-xs text-muted-foreground font-mono">{{ formatTTL(k.ttl) }}</TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </Card>
        </TabsContent>
      </Tabs>
    </div>

    <!-- Key Value Modal -->
    <Dialog v-model:open="keyModal.show">
      <DialogContent class="max-w-2xl">
        <DialogHeader>
          <DialogTitle class="font-mono text-sm truncate">{{ keyModal.key }}</DialogTitle>
        </DialogHeader>
        <div class="space-y-3">
          <div class="flex gap-3 flex-wrap">
            <div class="text-sm flex items-center gap-2">
              <span class="text-muted-foreground text-xs uppercase tracking-wider font-semibold">Type:</span>
              <Badge variant="secondary">{{ keyModal.type }}</Badge>
            </div>
            <div class="text-sm flex items-center gap-2">
              <span class="text-muted-foreground text-xs uppercase tracking-wider font-semibold">TTL:</span>
              <span class="font-mono text-foreground">{{ keyModal.ttl }}</span>
            </div>
          </div>
          <div class="bg-[#1e1e1e] rounded-xl overflow-hidden border border-primary/10">
            <pre class="p-4 text-[13px] text-green-400 font-mono overflow-auto max-h-80 whitespace-pre-wrap leading-relaxed">{{ keyModal.value }}</pre>
          </div>
        </div>
      </DialogContent>
    </Dialog>

    <!-- Toast -->
    <Transition name="fade">
      <div v-if="toast.show"
           :class="['fixed bottom-6 right-6 px-4 py-3 rounded-xl text-sm font-semibold shadow-lg z-50 flex items-center gap-2 border',
             toast.type === 'error' ? 'bg-destructive text-destructive-foreground border-destructive/20' : 'bg-foreground text-background border-foreground/10']">
        {{ toast.msg }}
      </div>
    </Transition>
  </DashboardLayout>
</template>
