<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useApi } from '@/composables/useApi'
import { useToastStore } from '@/stores/toast'
import type { NotificationConfig } from '@/types'

import Panel from '@/components/ds/data/Panel.vue'
import Button from '@/components/ds/core/Button.vue'
import Input from '@/components/ds/forms/Input.vue'
import Switch from '@/components/ds/forms/Switch.vue'

const api = useApi()
const toast = useToastStore()

const config = ref<NotificationConfig>({
  discord_webhook_url: null,
  discord_enabled: false,
  pushbullet_api_key: null,
  pushbullet_enabled: false,
  email_alerts_enabled: false,
  notify_wipe_start: true,
  notify_wipe_complete: true,
  notify_wipe_failed: true,
  notify_server_crash: true,
  notify_server_offline: true,
  notify_store_purchase: false,
})

const saving = ref(false)
const isLoading = ref(false)

const eventToggles = [
  { key: 'notify_wipe_start' as const, label: 'Wipe started', desc: 'When a wipe begins' },
  { key: 'notify_wipe_complete' as const, label: 'Wipe complete', desc: 'When a wipe finishes successfully' },
  { key: 'notify_wipe_failed' as const, label: 'Wipe failed', desc: 'When a wipe fails or rolls back' },
  { key: 'notify_server_crash' as const, label: 'Server crash', desc: 'When the server process crashes' },
  { key: 'notify_server_offline' as const, label: 'Server offline', desc: 'When the server goes unreachable' },
  { key: 'notify_store_purchase' as const, label: 'Store purchase', desc: 'When a player buys from the store' },
]

async function fetchConfig() {
  isLoading.value = true
  try {
    const data = await api.get<{ config: NotificationConfig }>('/notifications/config')
    config.value = data.config
  } catch {
    toast.error('Failed to load notification settings')
  } finally {
    isLoading.value = false
  }
}

async function saveConfig() {
  saving.value = true
  try {
    await api.put('/notifications/config', config.value)
    toast.success('Notification settings saved')
  } catch {
    toast.error('Failed to save notification settings')
  } finally {
    saving.value = false
  }
}

// Coerce nullable string fields to string for DS Input (which expects string, not string|null)
const discordWebhookUrl = computed<string>({
  get: () => config.value.discord_webhook_url ?? '',
  set: (v) => { config.value.discord_webhook_url = v || null },
})
const pushbulletApiKey = computed<string>({
  get: () => config.value.pushbullet_api_key ?? '',
  set: (v) => { config.value.pushbullet_api_key = v || null },
})

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

<template>
  <div class="notifs">
    <!-- Page head -->
    <div class="page__head">
      <div>
        <div class="t-eyebrow">Monitoring</div>
        <h1 class="page__title">Notifications</h1>
      </div>
      <Button
        size="sm"
        icon="save"
        :loading="saving"
        @click="saveConfig"
      >
        {{ saving ? 'Saving...' : 'Save changes' }}
      </Button>
    </div>

    <!-- Discord webhook -->
    <Panel title="Discord webhook" subtitle="Send notifications to a Discord channel" eyebrow="Channel">
      <template #actions>
        <Switch v-model="config.discord_enabled" />
      </template>
      <Input
        v-model="discordWebhookUrl"
        type="url"
        placeholder="https://discord.com/api/webhooks/..."
        :disabled="!config.discord_enabled"
        :mono="true"
      />
    </Panel>

    <!-- Pushbullet -->
    <Panel title="Pushbullet" subtitle="Push notifications to your devices" eyebrow="Channel">
      <template #actions>
        <Switch v-model="config.pushbullet_enabled" />
      </template>
      <Input
        v-model="pushbulletApiKey"
        placeholder="Pushbullet API key"
        :disabled="!config.pushbullet_enabled"
        :mono="true"
      />
    </Panel>

    <!-- Email alerts -->
    <Panel title="Email alerts" subtitle="Send critical alerts to your registered email" eyebrow="Channel">
      <template #actions>
        <Switch v-model="config.email_alerts_enabled" />
      </template>
      <!-- No additional fields for email — toggle only -->
    </Panel>

    <!-- Event triggers -->
    <Panel title="Event triggers" subtitle="Choose which events fire notifications" eyebrow="Routing">
      <div class="triggers">
        <div
          v-for="toggle in eventToggles"
          :key="toggle.key"
          class="trigger-row"
        >
          <div class="trigger-text">
            <span class="trigger-label">{{ toggle.label }}</span>
            <span class="trigger-desc">{{ toggle.desc }}</span>
          </div>
          <Switch v-model="config[toggle.key]" />
        </div>
      </div>
    </Panel>
  </div>
</template>

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

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

/* Event triggers */
.triggers { display: flex; flex-direction: column; gap: 2px; }
.trigger-row {
  display: flex; align-items: center; justify-content: space-between; gap: 16px;
  padding: 11px 4px;
  border-bottom: 1px solid var(--border-subtle);
}
.trigger-row:last-child { border-bottom: 0; }
.trigger-text { display: flex; flex-direction: column; gap: 2px; }
.trigger-label { font-size: var(--text-sm); font-weight: 500; color: var(--text-primary); }
.trigger-desc { font-size: var(--text-xs); color: var(--text-tertiary); }
</style>
