<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useApi } from '@/composables/useApi'
import { AlertTriangle, Save, Loader2 } from 'lucide-vue-next'
import { safeDate } from '@/utils/formatters'

interface AlertConfig {
  population_drop_enabled: boolean
  population_drop_threshold_percent: number
  fps_degradation_enabled: boolean
  fps_threshold: number
  notify_discord: boolean
  notify_pushbullet: boolean
  notify_email: boolean
}

interface AlertHistoryEntry {
  id: string
  triggered_at: string
  alert_type: string
  severity: 'info' | 'warning' | 'critical'
  title: string
  message: string
}

const api = useApi()
const config = ref<AlertConfig>({
  population_drop_enabled: false,
  population_drop_threshold_percent: 50,
  fps_degradation_enabled: false,
  fps_threshold: 30,
  notify_discord: false,
  notify_pushbullet: false,
  notify_email: false,
})
const history = ref<AlertHistoryEntry[]>([])
const isSaving = ref(false)
const isLoading = ref(false)

async function fetchConfig() {
  isLoading.value = true
  try {
    config.value = await api.get<AlertConfig>('/alerts/config')
  } finally {
    isLoading.value = false
  }
}

async function fetchHistory() {
  history.value = await api.get<AlertHistoryEntry[]>('/alerts/history?limit=50')
}

async function saveConfig() {
  isSaving.value = true
  try {
    await api.put('/alerts/config', config.value)
    alert('Alert configuration saved')
  } catch (err) {
    alert(err instanceof Error ? err.message : 'Failed to save configuration')
  } finally {
    isSaving.value = false
  }
}

function getSeverityColor(severity: string): string {
  switch (severity) {
    case 'info': return 'bg-blue-500/10 text-blue-400'
    case 'warning': return 'bg-yellow-500/10 text-yellow-400'
    case 'critical': return 'bg-red-500/10 text-red-400'
    default: return 'bg-neutral-700/50 text-neutral-400'
  }
}

onMounted(() => {
  fetchConfig()
  fetchHistory()
})
</script>

<template>
  <div class="p-6 space-y-6">
    <!-- Header -->
    <div class="flex items-center gap-3">
      <AlertTriangle class="w-5 h-5 text-oxide-500" />
      <h1 class="text-2xl font-bold text-neutral-100">Alerts</h1>
    </div>

    <!-- Alert Configuration -->
    <div class="bg-neutral-900 border border-neutral-800 rounded-lg p-5">
      <h2 class="text-sm font-medium text-neutral-400 uppercase tracking-wider mb-4">Alert Configuration</h2>

      <div v-if="isLoading" class="py-8 flex justify-center">
        <Loader2 class="w-6 h-6 text-oxide-500 animate-spin" />
      </div>

      <div v-else class="space-y-6">
        <!-- Population Drop Alert -->
        <div class="space-y-3">
          <div class="flex items-center justify-between">
            <label class="text-sm font-medium text-neutral-200">Population Drop Alert</label>
            <button
              @click="config.population_drop_enabled = !config.population_drop_enabled"
              class="relative inline-flex h-6 w-11 items-center rounded-full transition-colors"
              :class="config.population_drop_enabled ? 'bg-oxide-500' : 'bg-neutral-700'"
            >
              <span
                class="inline-block h-4 w-4 transform rounded-full bg-white transition-transform"
                :class="config.population_drop_enabled ? 'translate-x-6' : 'translate-x-1'"
              />
            </button>
          </div>
          <div v-if="config.population_drop_enabled">
            <label class="block text-xs text-neutral-500 mb-2">Threshold (%)</label>
            <input
              v-model.number="config.population_drop_threshold_percent"
              type="range"
              min="10"
              max="100"
              class="w-full h-2 bg-neutral-700 rounded-lg appearance-none cursor-pointer accent-oxide-500"
            />
            <div class="text-xs text-neutral-400 mt-1">{{ config.population_drop_threshold_percent }}%</div>
          </div>
        </div>

        <!-- FPS Degradation Alert -->
        <div class="space-y-3">
          <div class="flex items-center justify-between">
            <label class="text-sm font-medium text-neutral-200">FPS Degradation Alert</label>
            <button
              @click="config.fps_degradation_enabled = !config.fps_degradation_enabled"
              class="relative inline-flex h-6 w-11 items-center rounded-full transition-colors"
              :class="config.fps_degradation_enabled ? 'bg-oxide-500' : 'bg-neutral-700'"
            >
              <span
                class="inline-block h-4 w-4 transform rounded-full bg-white transition-transform"
                :class="config.fps_degradation_enabled ? 'translate-x-6' : 'translate-x-1'"
              />
            </button>
          </div>
          <div v-if="config.fps_degradation_enabled">
            <label class="block text-xs text-neutral-500 mb-2">FPS Threshold</label>
            <input
              v-model.number="config.fps_threshold"
              type="number"
              min="10"
              max="60"
              class="w-full px-3 py-2 bg-neutral-800 border border-neutral-700 rounded-lg text-neutral-200 focus:outline-none focus:ring-2 focus:ring-oxide-500"
            />
          </div>
        </div>

        <!-- Notification Channels -->
        <div class="border-t border-neutral-800 pt-4">
          <h3 class="text-sm font-medium text-neutral-400 uppercase tracking-wider mb-3">Notification Channels</h3>
          <div class="space-y-2">
            <label class="flex items-center gap-3 cursor-pointer">
              <input
                v-model="config.notify_discord"
                type="checkbox"
                class="w-4 h-4 rounded border-neutral-700 bg-neutral-800 text-oxide-500 focus:ring-2 focus:ring-oxide-500"
              />
              <span class="text-sm text-neutral-200">Discord</span>
            </label>
            <label class="flex items-center gap-3 cursor-pointer">
              <input
                v-model="config.notify_pushbullet"
                type="checkbox"
                class="w-4 h-4 rounded border-neutral-700 bg-neutral-800 text-oxide-500 focus:ring-2 focus:ring-oxide-500"
              />
              <span class="text-sm text-neutral-200">Pushbullet</span>
            </label>
            <label class="flex items-center gap-3 cursor-pointer">
              <input
                v-model="config.notify_email"
                type="checkbox"
                class="w-4 h-4 rounded border-neutral-700 bg-neutral-800 text-oxide-500 focus:ring-2 focus:ring-oxide-500"
              />
              <span class="text-sm text-neutral-200">Email</span>
            </label>
          </div>
        </div>

        <!-- Save Button -->
        <button
          @click="saveConfig"
          :disabled="isSaving"
          class="flex items-center gap-2 px-4 py-2 bg-oxide-500 hover:bg-oxide-600 disabled:opacity-50 text-white font-medium rounded-lg transition-colors"
        >
          <Loader2 v-if="isSaving" class="w-4 h-4 animate-spin" />
          <Save v-else class="w-4 h-4" />
          Save Configuration
        </button>
      </div>
    </div>

    <!-- Alert History -->
    <div class="bg-neutral-900 border border-neutral-800 rounded-lg overflow-hidden">
      <div class="p-5 border-b border-neutral-800">
        <h2 class="text-sm font-medium text-neutral-400 uppercase tracking-wider">Alert History</h2>
      </div>
      <div v-if="history.length === 0" class="p-8 text-center text-neutral-500">
        No alerts triggered yet.
      </div>
      <table v-else class="w-full">
        <thead class="bg-neutral-800/50 border-b border-neutral-800">
          <tr>
            <th class="px-4 py-3 text-left text-xs font-medium text-neutral-400 uppercase tracking-wider">Triggered</th>
            <th class="px-4 py-3 text-left text-xs font-medium text-neutral-400 uppercase tracking-wider">Type</th>
            <th class="px-4 py-3 text-left text-xs font-medium text-neutral-400 uppercase tracking-wider">Severity</th>
            <th class="px-4 py-3 text-left text-xs font-medium text-neutral-400 uppercase tracking-wider">Title</th>
            <th class="px-4 py-3 text-left text-xs font-medium text-neutral-400 uppercase tracking-wider">Message</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-neutral-800">
          <tr v-for="alert in history" :key="alert.id" class="hover:bg-neutral-800/30">
            <td class="px-4 py-3 text-sm text-neutral-400">{{ safeDate(alert.triggered_at) }}</td>
            <td class="px-4 py-3 text-sm text-neutral-400">{{ alert.alert_type }}</td>
            <td class="px-4 py-3">
              <span
                class="text-xs font-medium px-2 py-0.5 rounded-full capitalize"
                :class="getSeverityColor(alert.severity)"
              >
                {{ alert.severity }}
              </span>
            </td>
            <td class="px-4 py-3 text-sm text-neutral-200">{{ alert.title }}</td>
            <td class="px-4 py-3 text-sm text-neutral-400">{{ alert.message }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
