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

const ui = useUiStore()

const events = ref<SyncEvent[]>([])
const loading = ref(false)
const filterDocNumber = ref('')
const filterTable = ref('')

async function load() {
  loading.value = true
  try {
    const { data } = await configApi.getSyncEvents({ limit: 100 })
    events.value = data.events
  } catch {
    ui.showToast('Failed to load events', 'error')
  } finally {
    loading.value = false
  }
}

const filteredEvents = computed(() => {
  let result = events.value
  if (filterDocNumber.value) {
    const q = filterDocNumber.value.toLowerCase()
    result = result.filter(e => e.doc_number?.toLowerCase().includes(q))
  }
  if (filterTable.value) {
    const q = filterTable.value.toLowerCase()
    result = result.filter(e => e.local_table.toLowerCase().includes(q))
  }
  return result
})

function formatTime(iso: string): string {
  const d = new Date(iso)
  return d.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' })
}

onMounted(load)
</script>

<template>
  <div class="space-y-4">
    <div class="card">
      <div class="flex items-center justify-between mb-3">
        <h3 class="font-semibold text-sm">Sync Events</h3>
        <button @click="load" :disabled="loading" class="btn-secondary text-xs">
          {{ loading ? 'Loading...' : 'Refresh' }}
        </button>
      </div>
      <p class="text-xs text-dark-400 mb-4">Debug view of change detection events. Each row represents a single column change detected during sync.</p>

      <!-- Filters -->
      <div class="grid grid-cols-2 gap-3 mb-4">
        <div>
          <label class="text-xs text-dark-400 mb-1 block">Filter by Doc#</label>
          <input v-model="filterDocNumber" placeholder="Document number..." class="input-field w-full" />
        </div>
        <div>
          <label class="text-xs text-dark-400 mb-1 block">Filter by Table</label>
          <input v-model="filterTable" placeholder="Table name..." class="input-field w-full" />
        </div>
      </div>

      <div v-if="loading" class="text-dark-500 text-sm text-center py-6">Loading events...</div>

      <div v-else-if="!filteredEvents.length" class="text-dark-500 text-sm text-center py-6">
        No sync events found. Events are created when watched columns change during sync.
      </div>

      <div v-else class="overflow-x-auto">
        <table class="w-full text-xs">
          <thead>
            <tr class="text-dark-500 border-b border-dark-700">
              <th class="text-left py-1.5 px-2 font-medium">Time</th>
              <th class="text-left py-1.5 px-2 font-medium">Table</th>
              <th class="text-left py-1.5 px-2 font-medium">Doc#</th>
              <th class="text-left py-1.5 px-2 font-medium">Column</th>
              <th class="text-left py-1.5 px-2 font-medium">Change</th>
              <th class="text-left py-1.5 px-2 font-medium">Type</th>
              <th class="text-center py-1.5 px-2 font-medium">Processed</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="evt in filteredEvents"
              :key="evt.id"
              class="border-b border-dark-800 hover:bg-dark-900/50"
            >
              <td class="py-1.5 px-2 text-dark-400 whitespace-nowrap">{{ formatTime(evt.detected_at) }}</td>
              <td class="py-1.5 px-2 text-dark-300 font-mono">{{ evt.local_table }}</td>
              <td class="py-1.5 px-2">
                <span v-if="evt.doc_number" class="text-primary-400 font-medium">{{ evt.doc_number }}</span>
                <span v-else class="text-dark-600">--</span>
              </td>
              <td class="py-1.5 px-2 text-dark-300 font-mono">{{ evt.column_name }}</td>
              <td class="py-1.5 px-2">
                <span v-if="evt.old_value" class="text-red-400 line-through mr-1">{{ evt.old_value }}</span>
                <span v-if="evt.old_value && evt.new_value" class="text-dark-600 mr-1">&rarr;</span>
                <span v-if="evt.new_value" class="text-green-400">{{ evt.new_value }}</span>
              </td>
              <td class="py-1.5 px-2">
                <span
                  :class="{
                    'text-blue-400': evt.change_type === 'changed',
                    'text-green-400': evt.change_type === 'added',
                    'text-red-400': evt.change_type === 'removed',
                  }"
                  class="font-medium"
                >{{ evt.change_type }}</span>
              </td>
              <td class="py-1.5 px-2 text-center">
                <span v-if="evt.processed" class="text-green-400">Y</span>
                <span v-else class="text-yellow-400">N</span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>
