<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useApi } from '@/composables/useApi'
import { useToastStore } from '@/stores/toast'
import { useThemeGame } from '@/composables/useThemeGame'
import type { ChatMessage } from '@/types'
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 Icon from '@/components/ds/core/Icon.vue'
import IconButton from '@/components/ds/core/IconButton.vue'
import Input from '@/components/ds/forms/Input.vue'
import EmptyState from '@/components/ds/feedback/EmptyState.vue'
import Tabs from '@/components/ds/navigation/Tabs.vue'

const api = useApi()
const toast = useToastStore()
const { activeGame } = useThemeGame()
const playerIdLabel = computed(() => activeGame.value === 'rust' || activeGame.value === 'all' ? 'Steam ID' : 'Player ID')

const messages = ref<ChatMessage[]>([])
const isLoading = ref(false)
const searchQuery = ref('')
const channelFilter = ref<'all' | 'global' | 'team' | 'server'>('all')

const filteredMessages = computed(() => {
  let result = messages.value

  if (channelFilter.value !== 'all') {
    result = result.filter(m => m.channel === channelFilter.value)
  }

  if (searchQuery.value.trim()) {
    const q = searchQuery.value.toLowerCase()
    result = result.filter(m =>
      m.player_name.toLowerCase().includes(q) ||
      m.message.toLowerCase().includes(q) ||
      m.steam_id.includes(q)
    )
  }

  return result
})

const channelTabItems = computed(() => [
  { value: 'all', label: 'All', count: messages.value.length },
  { value: 'global', label: 'Global' },
  { value: 'team', label: 'Team' },
  { value: 'server', label: 'Server' },
])

function channelTone(channel: string): 'accent' | 'info' | 'neutral' {
  switch (channel) {
    case 'global': return 'accent'
    case 'team': return 'info'
    default: return 'neutral'
  }
}

function formatTime(iso: string): string {
  return new Date(iso).toLocaleTimeString('en-US', { hour12: false })
}

function formatDate(iso: string): string {
  return new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
}

async function fetchMessages() {
  isLoading.value = true
  try {
    const data = await api.get<{ messages: ChatMessage[] }>('/chat')
    messages.value = data.messages
  } catch {
    toast.error('Failed to load chat messages')
  } finally {
    isLoading.value = false
  }
}

async function toggleFlag(msg: ChatMessage) {
  try {
    await api.put(`/chat/${msg.id}/flag`, { flagged: !msg.flagged })
    msg.flagged = !msg.flagged
  } catch {
    toast.error('Failed to update flag')
  }
}

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

<template>
  <div class="clv">
    <!-- Page head -->
    <div class="clv__head">
      <div class="clv__head-id">
        <div class="clv__head-chip">
          <Icon name="message-square" :size="20" :stroke-width="2" />
        </div>
        <div>
          <div class="t-eyebrow">Chat log</div>
          <h1 class="clv__title">Chat log</h1>
        </div>
      </div>
      <div class="clv__head-actions">
        <div class="clv__stat-pill">
          <span class="clv__stat-num">{{ messages.length }}</span>
          <span class="clv__stat-label">messages</span>
        </div>
        <Button
          variant="secondary"
          size="sm"
          icon="refresh-cw"
          :loading="isLoading"
          :disabled="isLoading"
          @click="fetchMessages"
        >Refresh</Button>
      </div>
    </div>

    <!-- Filters -->
    <div class="clv__filters">
      <Input
        v-model="searchQuery"
        icon="search"
        :placeholder="`Search messages, players, or ${playerIdLabel}s…`"
        size="sm"
        style="max-width: 340px;"
      />
      <Tabs v-model="channelFilter" :items="channelTabItems" />
    </div>

    <!-- Messages panel -->
    <Panel :flush-body="true">
      <!-- Empty state -->
      <EmptyState
        v-if="filteredMessages.length === 0 && !isLoading"
        icon="message-square"
        :title="searchQuery ? 'No messages found' : 'No chat messages'"
        :description="searchQuery
          ? `No messages matching &quot;${searchQuery}&quot;.`
          : 'No chat messages yet. Messages will appear when the server is active.'"
      />

      <!-- Loading -->
      <div v-else-if="isLoading && filteredMessages.length === 0" class="clv__loading">
        <Icon name="loader" :size="20" class="clv__spin" />
        <span>Loading chat messages…</span>
      </div>

      <!-- Message list -->
      <div v-else class="clv__messages">
        <div
          v-for="msg in filteredMessages"
          :key="msg.id"
          class="clv__row"
          :class="{ 'clv__row--flagged': msg.flagged }"
        >
          <!-- Timestamp -->
          <div class="clv__ts">
            <span class="clv__date">{{ formatDate(msg.created_at) }}</span>
            <span class="clv__time">{{ formatTime(msg.created_at) }}</span>
          </div>

          <!-- Channel badge -->
          <Badge :tone="channelTone(msg.channel)" size="md">{{ msg.channel }}</Badge>

          <!-- Message body -->
          <div class="clv__body">
            <span class="clv__player">{{ msg.player_name }}</span>
            <span class="clv__steam">{{ msg.steam_id }}</span>
            <p class="clv__text">{{ msg.message }}</p>
          </div>

          <!-- Flag toggle -->
          <IconButton
            icon="bookmark"
            :variant="msg.flagged ? 'accent' : 'ghost'"
            size="sm"
            :label="msg.flagged ? 'Unflag message' : 'Flag message'"
            @click="toggleFlag(msg)"
          />
        </div>
      </div>
    </Panel>
  </div>
</template>

<style scoped>
.clv { max-width: 1100px; margin: 0 auto; display: flex; flex-direction: column; gap: 16px; }

/* Page head */
.clv__head {
  display: flex; align-items: flex-end; justify-content: space-between;
  flex-wrap: wrap; gap: 12px;
}
.clv__head-id { display: flex; align-items: center; gap: 12px; }
.clv__head-chip {
  width: 40px; height: 40px; flex: none; border-radius: var(--radius-md);
  display: flex; align-items: center; justify-content: center;
  color: var(--accent); background: var(--accent-soft);
  box-shadow: inset 0 0 0 1px var(--accent-border);
}
.clv__title {
  font-size: var(--text-2xl); font-weight: 700; letter-spacing: -0.02em;
  color: var(--text-primary); margin-top: 3px;
}
.clv__head-actions { display: flex; align-items: center; gap: 12px; }

/* Stat pill */
.clv__stat-pill { display: flex; align-items: center; gap: 6px; }
.clv__stat-num { font-family: var(--font-mono); font-size: var(--text-sm); font-weight: 700; color: var(--text-primary); font-variant-numeric: tabular-nums; }
.clv__stat-label { font-size: var(--text-xs); color: var(--text-tertiary); }

/* Filters */
.clv__filters { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }

/* Loading */
.clv__loading {
  display: flex; align-items: center; justify-content: center; gap: 10px;
  padding: 48px; color: var(--text-tertiary); font-size: var(--text-sm);
}
@keyframes clv-spin { to { transform: rotate(360deg); } }
.clv__spin { animation: clv-spin 0.7s linear infinite; }

/* Messages */
.clv__messages { display: flex; flex-direction: column; }
.clv__row {
  display: flex; align-items: flex-start; gap: 14px;
  padding: 12px 16px;
  border-bottom: 1px solid var(--border-subtle);
  transition: var(--transition-colors);
}
.clv__row:last-child { border-bottom: 0; }
.clv__row:hover { background: var(--surface-hover); }
.clv__row--flagged {
  background: var(--status-offline-soft);
  border-left: 3px solid var(--status-offline-border);
}
.clv__row--flagged:hover { background: var(--status-offline-soft); filter: brightness(1.04); }

/* Timestamp */
.clv__ts { display: flex; flex-direction: column; align-items: flex-end; min-width: 68px; flex: none; padding-top: 1px; }
.clv__date { font-family: var(--font-mono); font-size: var(--text-xs); color: var(--text-tertiary); }
.clv__time { font-family: var(--font-mono); font-size: var(--text-xs); color: var(--text-muted); }

/* Message body */
.clv__body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
.clv__player { font-size: var(--text-sm); font-weight: 600; color: var(--accent-text); }
.clv__steam { font-family: var(--font-mono); font-size: var(--text-xs); color: var(--text-muted); margin-left: 8px; }
.clv__text { font-size: var(--text-sm); color: var(--text-secondary); line-height: 1.5; word-break: break-word; margin: 0; }
</style>
