<template>
  <div class="min-h-screen bg-background">
    <NuxtLayout name="default">
      <main class="container mx-auto px-4 py-8">
        <div v-if="loading" class="text-center py-12">Loading...</div>
        <div v-else-if="error" class="text-destructive">Error: {{ error }}</div>
        <div v-else>
          <div class="flex items-center justify-between mb-6">
            <h1 class="text-3xl font-bold">Activity Log</h1>
            <button
              @click="fetchActivities"
              class="px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90"
            >
              Refresh
            </button>
          </div>

          <div class="grid gap-4">
            <div
              v-for="activity in activities"
              :key="activity.id"
              class="p-6 border rounded-lg bg-card"
            >
              <div class="flex items-center justify-between mb-2">
                <h3 class="text-lg font-semibold">{{ activity.action }}</h3>
                <span class="text-xs text-muted-foreground">{{ formatDate(activity.createdAt) }}</span>
              </div>
              <p class="text-sm text-muted-foreground mb-2">
                {{ activity.description || 'No description' }}
              </p>
              <div class="text-sm text-muted-foreground">
                <div>Subject: {{ activity.subjectType }} • {{ activity.subjectId }}</div>
                <div>Causer: {{ activity.causerId || 'System' }}</div>
              </div>
            </div>
          </div>
        </div>
      </main>
    </NuxtLayout>
  </div>
</template>

<script setup lang="ts">
const { api } = useApi()

const activities = ref<any[]>([])
const loading = ref(true)
const error = ref<string | null>(null)

const formatDate = (value?: string) => {
  if (!value) return '—'
  const date = new Date(value)
  return date.toLocaleString()
}

const fetchActivities = async () => {
  try {
    loading.value = true
    activities.value = await api.get('/activity-log')
  } catch (e: any) {
    error.value = e.message
  } finally {
    loading.value = false
  }
}

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