<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { configApi } from '../../services/configApi'
import { useUiStore } from '../../stores/ui'
import type { NotificationEntry } from '../../types'

const ui = useUiStore()
const notifications = ref<NotificationEntry[]>([])
const loading = ref(false)
const statusFilter = ref('')

async function load() {
  loading.value = true
  try {
    const { data } = await configApi.getNotificationHistory({
      limit: 100,
      status: statusFilter.value || undefined,
    })
    notifications.value = data.notifications
  } catch {
    ui.showToast('Failed to load notification history', 'error')
  } finally {
    loading.value = false
  }
}

function statusColor(status: string) {
  switch (status) {
    case 'sent': return 'text-green-400'
    case 'failed': return 'text-red-400'
    case 'pending': return 'text-yellow-400'
    default: return 'text-dark-400'
  }
}

function formatDate(d: string) {
  return new Date(d).toLocaleString()
}

onMounted(load)
</script>

<template>
  <div class="card">
    <div class="flex items-center justify-between mb-3">
      <h3 class="font-semibold text-sm">Notification History</h3>
      <div class="flex items-center gap-2">
        <select v-model="statusFilter" @change="load" class="input-field text-xs py-1">
          <option value="">All</option>
          <option value="sent">Sent</option>
          <option value="pending">Pending</option>
          <option value="failed">Failed</option>
        </select>
        <button @click="load" class="text-xs text-dark-400 hover:text-dark-200">Refresh</button>
      </div>
    </div>

    <div v-if="loading" class="text-dark-500 text-sm py-4 text-center">Loading...</div>
    <div v-else-if="!notifications.length" class="text-dark-500 text-sm py-4 text-center">
      No notifications sent yet.
    </div>
    <div v-else class="space-y-2 max-h-96 overflow-y-auto">
      <div v-for="n in notifications" :key="n.id" class="p-3 bg-dark-900 rounded-lg">
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-2">
            <span :class="statusColor(n.status)" class="text-xs font-semibold uppercase">{{ n.status }}</span>
            <span class="font-mono text-sm">{{ n.doc_number }}</span>
          </div>
          <span class="text-xs text-dark-500">{{ formatDate(n.sent_at || n.created_at) }}</span>
        </div>
        <div class="text-sm text-dark-300 mt-1">{{ n.subject }}</div>
        <div class="text-xs text-dark-500 mt-0.5">To: {{ n.email }}</div>
        <div v-if="n.error_message" class="text-xs text-red-400 mt-1">{{ n.error_message }}</div>
      </div>
    </div>
  </div>
</template>
