<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useApi } from '@/composables/useApi'
import { useToastStore } from '@/stores/toast'
import { safeDate } from '@/utils/formatters'
import Panel from '@/components/ds/data/Panel.vue'
import Button from '@/components/ds/core/Button.vue'
import Badge from '@/components/ds/core/Badge.vue'
import Switch from '@/components/ds/forms/Switch.vue'
import Input from '@/components/ds/forms/Input.vue'
import Checkbox from '@/components/ds/forms/Checkbox.vue'
import EmptyState from '@/components/ds/feedback/EmptyState.vue'

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 toast = useToastStore()
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)
    toast.success('Alert configuration saved')
  } catch (err) {
    toast.error(err instanceof Error ? err.message : 'Failed to save configuration')
  } finally {
    isSaving.value = false
  }
}

function severityTone(severity: string): 'info' | 'warn' | 'offline' | 'neutral' {
  if (severity === 'info') return 'info'
  if (severity === 'warning') return 'warn'
  if (severity === 'critical') return 'offline'
  return 'neutral'
}

// Range input handler (range emits string, keep numeric in config)
function onThresholdInput(e: Event) {
  const val = parseInt((e.target as HTMLInputElement).value, 10)
  if (!isNaN(val)) {
    config.value.population_drop_threshold_percent = val
  }
}

// FPS threshold: DS Input binds string; sync via a string ref
const fpsStr = ref(String(config.value.fps_threshold))
function onFpsUpdate(val: string | undefined) {
  fpsStr.value = val ?? ''
  const n = parseInt(val ?? '', 10)
  if (!isNaN(n)) config.value.fps_threshold = n
}

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

<template>
  <div class="alerts">
    <!-- Page head -->
    <div class="page__head">
      <div>
        <div class="t-eyebrow">Monitoring</div>
        <h1 class="page__title">Alerts</h1>
      </div>
    </div>

    <!-- Alert configuration -->
    <Panel title="Alert configuration" subtitle="Trigger conditions and notification channels">
      <div v-if="isLoading" class="loading-row">
        <span class="cc-btn__spin" style="width:20px;height:20px;border-width:2.5px;" />
      </div>

      <div v-else class="config-body">
        <!-- Triggers section -->
        <div class="config-section">
          <div class="t-eyebrow config-section__eyebrow">Triggers</div>

          <!-- Population drop -->
          <div class="alert-rule">
            <div class="alert-rule__head">
              <div>
                <div class="alert-rule__name">Population drop alert</div>
                <div class="alert-rule__desc">Fire when player count falls by this percentage</div>
              </div>
              <Switch v-model="config.population_drop_enabled" />
            </div>
            <div v-if="config.population_drop_enabled" class="alert-rule__body">
              <div class="range-field">
                <input
                  type="range"
                  :value="config.population_drop_threshold_percent"
                  min="10"
                  max="100"
                  class="cc-range"
                  @input="onThresholdInput"
                />
                <span class="range-value">{{ config.population_drop_threshold_percent }}%</span>
              </div>
            </div>
          </div>

          <!-- FPS degradation -->
          <div class="alert-rule">
            <div class="alert-rule__head">
              <div>
                <div class="alert-rule__name">FPS degradation alert</div>
                <div class="alert-rule__desc">Fire when server FPS drops below threshold</div>
              </div>
              <Switch v-model="config.fps_degradation_enabled" />
            </div>
            <div v-if="config.fps_degradation_enabled" class="alert-rule__body">
              <Input
                :model-value="fpsStr"
                label="FPS threshold"
                type="number"
                :mono="true"
                hint="Minimum acceptable FPS (10–60)"
                @update:model-value="onFpsUpdate"
              />
            </div>
          </div>
        </div>

        <!-- Notification channels -->
        <div class="config-section">
          <div class="t-eyebrow config-section__eyebrow">Notification channels</div>
          <div class="channels">
            <Checkbox v-model="config.notify_discord" label="Discord" />
            <Checkbox v-model="config.notify_pushbullet" label="Pushbullet" />
            <Checkbox v-model="config.notify_email" label="Email" />
          </div>
        </div>

        <!-- Save -->
        <Button icon="save" :loading="isSaving" @click="saveConfig">
          Save configuration
        </Button>
      </div>
    </Panel>

    <!-- Alert history -->
    <Panel :flush-body="true" title="Alert history">
      <EmptyState
        v-if="history.length === 0"
        icon="triangle-alert"
        title="No alerts triggered"
        description="Alerts will appear here when trigger conditions are met."
      />
      <table v-else class="cc-table">
        <thead>
          <tr>
            <th>Triggered</th>
            <th>Type</th>
            <th>Severity</th>
            <th>Title</th>
            <th>Message</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="entry in history" :key="entry.id">
            <td class="td-mono">{{ safeDate(entry.triggered_at) }}</td>
            <td>{{ entry.alert_type }}</td>
            <td>
              <Badge :tone="severityTone(entry.severity)">{{ entry.severity }}</Badge>
            </td>
            <td class="td-primary">{{ entry.title }}</td>
            <td>{{ entry.message }}</td>
          </tr>
        </tbody>
      </table>
    </Panel>
  </div>
</template>

<style scoped>
.alerts {
  max-width: 900px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 18px;
}

/* Page head */
.page__head {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  gap: 12px;
}
.page__title {
  font-size: var(--text-3xl);
  font-weight: 700;
  letter-spacing: -0.02em;
  color: var(--text-primary);
  margin-top: 4px;
}

/* Loading row */
.loading-row {
  display: flex;
  justify-content: center;
  padding: 40px;
}

/* Config body */
.config-body {
  display: flex;
  flex-direction: column;
  gap: 24px;
}
.config-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.config-section__eyebrow { margin-bottom: 4px; }

/* Alert rule card */
.alert-rule {
  background: var(--surface-raised);
  border-radius: var(--radius-md);
  box-shadow: var(--ring-default);
  overflow: hidden;
}
.alert-rule__head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 13px 15px;
}
.alert-rule__name {
  font-size: var(--text-sm);
  font-weight: 600;
  color: var(--text-primary);
}
.alert-rule__desc {
  font-size: var(--text-xs);
  color: var(--text-tertiary);
  margin-top: 2px;
}
.alert-rule__body {
  border-top: 1px solid var(--border-subtle);
  padding: 13px 15px;
}

/* Range slider */
.range-field {
  display: flex;
  align-items: center;
  gap: 14px;
}
.cc-range {
  flex: 1;
  height: 6px;
  border-radius: var(--radius-pill);
  appearance: none;
  background: var(--surface-active);
  cursor: pointer;
  accent-color: var(--accent);
  outline: 0;
}
.range-value {
  font-family: var(--font-mono);
  font-size: var(--text-sm);
  font-variant-numeric: tabular-nums;
  color: var(--accent-text);
  font-weight: 600;
  min-width: 36px;
  text-align: right;
}

/* Channels */
.channels {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* Table */
.cc-table {
  width: 100%;
  border-collapse: collapse;
  font-size: var(--text-sm);
}
.cc-table thead tr {
  border-bottom: 1px solid var(--border-subtle);
  background: var(--surface-inset);
}
.cc-table th {
  padding: 10px 16px;
  text-align: left;
  font-size: var(--text-xs);
  font-weight: 600;
  color: var(--text-tertiary);
  white-space: nowrap;
}
.cc-table tbody tr {
  border-bottom: 1px solid var(--border-subtle);
  transition: var(--transition-colors);
}
.cc-table tbody tr:last-child { border-bottom: 0; }
.cc-table tbody tr:hover { background: var(--surface-hover); }
.cc-table td {
  padding: 11px 16px;
  color: var(--text-secondary);
  vertical-align: middle;
}
.td-primary { color: var(--text-primary); font-weight: 500; }
.td-mono { font-family: var(--font-mono); font-variant-numeric: tabular-nums; }
</style>
