<script setup>
import { ref } 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 { Separator } from '@/components/ui/separator'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'

const API = '/api/limit'
const identityKey = ref('')
const loading = ref(false)
const resetting = ref(false)
const msg = ref({ text: '', type: '' })
const stats = ref(null)

async function checkInfo() {
  const key = identityKey.value.trim()
  if (!key) return
  loading.value = true
  stats.value = null
  msg.value = { text: '', type: '' }
  try {
    const r = await fetch(`${API}/info?identity_key=${encodeURIComponent(key)}`)
    const d = await r.json()
    if (d.status === 'success') {
      const info = d.info || {}
      stats.value = {
        limit: Number(info.limit || 0),
        used: Number(info.used || 0),
        remaining: Number(info.remaining || 0),
        isAuth: info.is_authenticated,
        isBlocked: Number(info.remaining || 0) <= 0 && Number(info.limit || 0) > 0,
        pct: info.limit > 0 ? Math.min(100, Math.round((info.used / info.limit) * 100)) : 0
      }
    } else {
      msg.value = { text: d.message || 'Không thể lấy thông tin', type: 'error' }
    }
  } catch (e) {
    msg.value = { text: 'Lỗi: ' + e.message, type: 'error' }
  } finally {
    loading.value = false
  }
}

async function resetLimit() {
  const key = identityKey.value.trim()
  if (!key) return
  if (!confirm(`Reset limit cho ${key}?\nSố tin nhắn đã gửi hôm nay sẽ về 0.`)) return
  resetting.value = true
  try {
    const r = await fetch(`${API}/reset`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ identity_key: key })
    })
    const d = await r.json()
    if (d.status === 'success') {
      msg.value = { text: '✅ ' + d.message, type: 'success' }
      setTimeout(checkInfo, 300)
    } else {
      msg.value = { text: '❌ ' + (d.message || 'Không thể reset'), type: 'error' }
    }
  } catch (e) {
    msg.value = { text: 'Lỗi: ' + e.message, type: 'error' }
  } finally {
    resetting.value = false
  }
}
</script>

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

      <!-- Header -->
      <div>
        <h1 class="text-3xl font-bold tracking-tight text-foreground">Rate Limit Manager</h1>
        <p class="text-sm text-muted-foreground mt-1">Kiểm tra và reset giới hạn tin nhắn theo Identity Key</p>
      </div>

      <Separator />

      <!-- Search -->
      <Card>
        <CardContent class="p-5">
          <div class="flex gap-2">
            <Input
              v-model="identityKey"
              placeholder="Nhập Identity Key (device_id hoặc user_id)..."
              @keydown.enter="checkInfo"
              class="flex-1"
            />
            <Button @click="checkInfo" :disabled="loading || !identityKey.trim()">
              {{ loading ? '🔍 Đang tìm...' : '🔍 Kiểm tra' }}
            </Button>
          </div>
        </CardContent>
      </Card>

      <!-- Message -->
      <div v-if="msg.text"
           :class="['px-4 py-3 rounded-xl text-sm font-medium border',
             msg.type === 'error' ? 'bg-destructive/10 text-destructive border-destructive/20' : 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/10 dark:text-emerald-400 dark:border-emerald-900/30']">
        {{ msg.text }}
      </div>

      <!-- Stats -->
      <div v-if="stats">
        <!-- Status Cards -->
        <div class="grid grid-cols-2 gap-4 mb-4">
          <Card>
            <CardContent class="p-5">
              <p class="text-xs text-gray-400 mb-1">Trạng thái</p>
              <Badge :variant="stats.isBlocked ? 'destructive' : 'default'"
                     class="text-sm px-3 py-1">
                {{ stats.isBlocked ? '🚫 BỊ CHẶN' : '✅ BÌNH THƯỜNG' }}
              </Badge>
              <p class="text-xs text-gray-400 mt-2">
                {{ stats.isAuth ? '👤 User đã đăng nhập' : '🌐 Khách (Guest/Device)' }}
              </p>
            </CardContent>
          </Card>
          <Card>
            <CardContent class="p-5 space-y-2">
              <div class="flex justify-between text-sm">
                <span class="text-gray-500">Đã dùng</span>
                <span class="font-bold">{{ stats.used }} / {{ stats.limit }}</span>
              </div>
              <Progress :model-value="stats.pct"
                        :class="stats.pct >= 100 ? '[&>div]:bg-red-500' : stats.pct >= 80 ? '[&>div]:bg-orange-500' : '[&>div]:bg-green-500'" />
              <p class="text-xs text-gray-400 text-right">{{ stats.pct }}% đã dùng</p>
            </CardContent>
          </Card>
        </div>

        <!-- Stats mini-grid -->
        <div class="grid grid-cols-3 gap-4 mb-6">
          <Card class="border-border text-center">
            <CardContent class="p-5">
              <p class="text-3xl font-black text-foreground tabular-nums">{{ stats.limit }}</p>
              <p class="text-xs font-semibold text-muted-foreground uppercase tracking-wider mt-2">Tổng Limit</p>
            </CardContent>
          </Card>
          <Card class="border-border text-center">
            <CardContent class="p-5">
              <p class="text-3xl font-black text-foreground tabular-nums">{{ stats.used }}</p>
              <p class="text-xs font-semibold text-muted-foreground uppercase tracking-wider mt-2">Đã Dùng</p>
            </CardContent>
          </Card>
          <Card :class="['text-center border', stats.remaining <= 0 ? 'border-destructive/20 bg-destructive/5' : stats.remaining <= 2 ? 'border-amber-200 bg-amber-50/30 dark:bg-amber-900/10' : 'border-emerald-200 bg-emerald-50/30 dark:bg-emerald-900/10']">
            <CardContent class="p-5">
              <p class="text-3xl font-black tabular-nums"
                 :class="stats.remaining <= 0 ? 'text-destructive' : stats.remaining <= 2 ? 'text-amber-500' : 'text-emerald-500'">
                {{ stats.remaining }}
              </p>
              <p class="text-xs font-semibold text-muted-foreground uppercase tracking-wider mt-2">Còn Lại</p>
            </CardContent>
          </Card>
        </div>

        <!-- Reset Button -->
        <Button variant="destructive" class="w-full" @click="resetLimit" :disabled="resetting">
          {{ resetting ? '⏳ Đang reset...' : '⚡ Reset Limit về 0' }}
        </Button>
      </div>

    </div>
  </DashboardLayout>
</template>
