<template>
  <div class="admin-events">
    <!-- Page Header -->
    <div class="page-header">
      <div class="header-row">
        <div>
          <h1>Events</h1>
          <p>Create, manage, and monitor events and workshops</p>
        </div>
        <NuxtLink to="/admin/events/create" class="btn btn-primary">
          Create Event
        </NuxtLink>
      </div>
    </div>

    <!-- Filters -->
    <div class="filter-bar">
      <div class="field" style="margin-bottom: 0; flex: 1;">
        <input v-model="searchQuery" placeholder="Search events..." />
      </div>
      <div class="field" style="margin-bottom: 0;">
        <select v-model="typeFilter">
          <option value="all">All Types</option>
          <option value="community">Community</option>
          <option value="workshop">Workshop</option>
          <option value="social">Social</option>
          <option value="showcase">Showcase</option>
        </select>
      </div>
      <div class="field" style="margin-bottom: 0;">
        <select v-model="statusFilter">
          <option value="all">All Status</option>
          <option value="upcoming">Upcoming</option>
          <option value="ongoing">Ongoing</option>
          <option value="past">Past</option>
        </select>
      </div>
      <div class="field" style="margin-bottom: 0;">
        <select v-model="seriesFilter">
          <option value="all">All Events</option>
          <option value="series-only">Series Only</option>
          <option value="standalone-only">Standalone Only</option>
        </select>
      </div>
    </div>

    <!-- Events Table -->
    <div class="table-wrap">
      <div v-if="pending" class="loading-state">
        <div class="spinner" />
        <span>Loading events...</span>
      </div>

      <div v-else-if="error" class="error-state">
        Error loading events: {{ error }}
      </div>

      <table v-else-if="filteredEvents.length">
        <thead>
          <tr>
            <th class="col-title">Title</th>
            <th>Type</th>
            <th>Date</th>
            <th>Status</th>
            <th>Registration</th>
            <th>Tickets</th>
            <th class="col-actions-head">Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="event in filteredEvents" :key="event._id">
            <!-- Title -->
            <td class="col-title">
              <div class="event-title-cell">
                <div v-if="event.featureImage?.url && !event.featureImage?.publicId" class="event-thumb">
                  <img
                    :src="event.featureImage.url"
                    :alt="event.title"
                    @error="handleImageError($event)"
                  />
                </div>
                <div>
                  <span class="event-name">{{ event.title }}</span>
                  <span class="event-desc">{{ event.description.substring(0, 80) }}...</span>
                  <div v-if="event.series?.isSeriesEvent" class="series-tag">
                    <span class="series-pos">{{ event.series.position }}</span>
                    {{ event.series.title }}
                  </div>
                  <div class="event-flags">
                    <span v-if="event.membersOnly" class="flag">Members Only</span>
                    <span v-if="event.targetCircles?.length" class="flag">{{ event.targetCircles.join(', ') }}</span>
                    <span v-if="!event.isVisible" class="flag flag-dim">Hidden</span>
                  </div>
                </div>
              </div>
            </td>

            <!-- Type -->
            <td>
              <span class="badge" :class="event.eventType">{{ event.eventType }}</span>
            </td>

            <!-- Date -->
            <td class="col-date">
              <span class="date-main">{{ formatDate(event.startDate) }}</span>
              <span class="date-time">{{ formatTime(event.startDate) }}</span>
            </td>

            <!-- Status -->
            <td>
              <span :class="['status-pill', `status-${getEventStatus(event).toLowerCase()}`]">
                {{ getEventStatus(event) }}
              </span>
              <span v-if="event.isCancelled" class="status-pill status-cancelled">Cancelled</span>
            </td>

            <!-- Registration -->
            <td>
              <span v-if="event.registrationRequired" class="status-ok" style="font-size: 11px;">Required</span>
              <span v-else class="status-dim" style="font-size: 11px;">Optional</span>
              <span v-if="event.maxAttendees" class="reg-count">
                {{ event.registeredCount || 0 }} / {{ event.maxAttendees }}
              </span>
            </td>

            <!-- Tickets -->
            <td class="col-tickets">
              <template v-if="event.tickets?.enabled">
                <span class="ticket-on">Ticketing On</span>
                <span v-if="event.tickets?.requiresSeriesTicket" class="ticket-detail">Series Pass Required</span>
                <template v-else>
                  <span v-if="event.tickets.member?.available" class="ticket-detail">
                    Member: {{ event.tickets.member.isFree ? 'Free' : `$${event.tickets.member.price}` }}
                  </span>
                  <span v-if="event.tickets.public?.available" class="ticket-detail">
                    Public: ${{ event.tickets.public.price || 0 }}
                    <template v-if="event.tickets.public.quantity">
                      ({{ event.tickets.public.sold || 0 }}/{{ event.tickets.public.quantity }})
                    </template>
                  </span>
                </template>
              </template>
              <span v-else class="status-dim" style="font-size: 11px;">No tickets</span>
            </td>

            <!-- Actions -->
            <td class="col-actions">
              <NuxtLink
                :to="`/events/${event.slug || String(event._id)}`"
                class="link-btn"
                title="View"
              >View</NuxtLink>
              <button @click="editEvent(event)" class="link-btn" title="Edit">Edit</button>
              <button @click="duplicateEvent(event)" class="link-btn" title="Duplicate">Dup</button>
              <button @click="deleteEvent(event)" class="link-btn link-btn-danger" title="Delete">Del</button>
            </td>
          </tr>
        </tbody>
      </table>

      <div v-else class="empty-state">
        No events found matching your criteria
      </div>
    </div>
  </div>
</template>

<script setup>
definePageMeta({
  layout: 'admin',
  middleware: 'admin',
})

const {
  data: events,
  pending,
  error,
  refresh,
} = await useFetch('/api/admin/events')

const searchQuery = ref('')
const typeFilter = ref('all')
const statusFilter = ref('all')
const seriesFilter = ref('all')

const filteredEvents = computed(() => {
  if (!events.value) return []

  return events.value.filter((event) => {
    const matchesSearch =
      !searchQuery.value ||
      event.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      event.description.toLowerCase().includes(searchQuery.value.toLowerCase())

    const matchesType =
      typeFilter.value === 'all' || event.eventType === typeFilter.value

    const eventStatus = getEventStatus(event)
    const matchesStatus =
      statusFilter.value === 'all' || eventStatus.toLowerCase() === statusFilter.value

    const matchesSeries =
      seriesFilter.value === 'all' ||
      (seriesFilter.value === 'series-only' && event.series?.isSeriesEvent) ||
      (seriesFilter.value === 'standalone-only' && !event.series?.isSeriesEvent)

    return matchesSearch && matchesType && matchesStatus && matchesSeries
  })
})

const getEventStatus = (event) => {
  const now = new Date()
  const startDate = new Date(event.startDate)
  const endDate = new Date(event.endDate)

  if (now < startDate) return 'Upcoming'
  if (now >= startDate && now <= endDate) return 'Ongoing'
  return 'Past'
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  })
}

const formatTime = (dateString) => {
  return new Date(dateString).toLocaleTimeString('en-US', {
    hour: 'numeric',
    minute: '2-digit',
    hour12: true,
  })
}

const duplicateEvent = (event) => {
  const duplicateData = {
    title: `${event.title} (Copy)`,
    description: event.description,
    content: event.content || '',
    featureImage: event.featureImage || null,
    eventType: event.eventType,
    location: event.location || '',
    isOnline: event.isOnline,
    isVisible: true,
    isCancelled: false,
    cancellationMessage: '',
    targetCircles: event.targetCircles || [],
    maxAttendees: event.maxAttendees || '',
    registrationRequired: event.registrationRequired,
  }

  sessionStorage.setItem('duplicateEventData', JSON.stringify(duplicateData))
  navigateTo('/admin/events/create?duplicate=true')
}

const deleteEvent = async (event) => {
  if (confirm(`Are you sure you want to delete "${event.title}"?`)) {
    try {
      await $fetch(`/api/admin/events/${String(event._id)}`, {
        method: 'DELETE',
      })
      await refresh()
    } catch (error) {
      console.error('Failed to delete event:', error)
    }
  }
}

const handleImageError = (event) => {
  const img = event.target
  if (img?.parentElement) {
    img.parentElement.style.display = 'none'
  }
}

const editEvent = (event) => {
  navigateTo(`/admin/events/create?edit=${String(event._id)}`)
}
</script>

<style scoped>
.admin-events {
  max-width: 1100px;
  margin: 0 auto;
}

/* ---- PAGE HEADER ---- */
.page-header {
  padding: 28px 28px 20px;
  border-bottom: 1px dashed var(--border);
}

.header-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 16px;
}

.page-header h1 {
  font-family: 'Brygada 1918', serif;
  font-size: 24px;
  font-weight: 500;
  color: var(--text-bright);
  line-height: 1.2;
  margin-bottom: 4px;
}

.page-header p {
  font-size: 12px;
  color: var(--text-dim);
}

/* ---- FILTER BAR ---- */
.filter-bar {
  display: flex;
  gap: 12px;
  padding: 16px 28px;
  border-bottom: 1px dashed var(--border);
  flex-wrap: wrap;
}

/* ---- TABLE ---- */
.table-wrap {
  padding: 0 28px 28px;
}

table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
}

thead th {
  text-align: left;
  font-size: 10px;
  letter-spacing: 0.08em;
  text-transform: uppercase;
  color: var(--text-faint);
  padding: 14px 10px 10px;
  border-bottom: 1px dashed var(--border-d);
  font-weight: normal;
}

tbody tr {
  border-bottom: 1px dashed var(--border);
  transition: background 0.1s;
}

tbody tr:hover {
  background: var(--surface);
}

tbody td {
  padding: 14px 10px;
  color: var(--text);
  vertical-align: top;
}

/* ---- EVENT TITLE CELL ---- */
.col-title {
  min-width: 240px;
}

.event-title-cell {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.event-thumb {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
  overflow: hidden;
  border: 1px dashed var(--border);
}

.event-thumb img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.event-name {
  display: block;
  font-weight: 500;
  color: var(--text-bright);
  font-size: 13px;
  margin-bottom: 2px;
}

.event-desc {
  display: block;
  color: var(--text-faint);
  font-size: 11px;
  line-height: 1.4;
}

.series-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  margin-top: 6px;
  font-size: 10px;
  letter-spacing: 0.04em;
  text-transform: uppercase;
  color: var(--c-founder);
  border: 1px dashed rgba(138, 68, 32, 0.3);
  padding: 2px 8px;
}

.series-pos {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  font-size: 10px;
  font-weight: 600;
  color: var(--c-founder);
  border: 1px dashed rgba(138, 68, 32, 0.4);
  border-radius: 50%;
}

.event-flags {
  display: flex;
  gap: 8px;
  margin-top: 4px;
}

.flag {
  font-size: 10px;
  color: var(--text-dim);
}

.flag-dim {
  color: var(--text-faint);
}

/* ---- DATE COLUMN ---- */
.col-date {
  white-space: nowrap;
}

.date-main {
  display: block;
  color: var(--text);
  font-size: 12px;
}

.date-time {
  display: block;
  color: var(--text-faint);
  font-size: 11px;
  margin-top: 2px;
}

/* ---- STATUS PILLS ---- */
.status-pill {
  display: inline-block;
  font-size: 10px;
  letter-spacing: 0.06em;
  text-transform: uppercase;
  padding: 2px 8px;
  border: 1px dashed;
}

.status-upcoming {
  color: var(--candle);
  border-color: rgba(122, 90, 16, 0.3);
}

.status-ongoing {
  color: var(--green);
  border-color: rgba(74, 106, 56, 0.3);
}

.status-past {
  color: var(--text-faint);
  border-color: var(--border);
}

.status-cancelled {
  color: var(--ember);
  border-color: rgba(138, 68, 32, 0.3);
  margin-top: 4px;
}

.status-ok {
  color: var(--green);
}

.status-dim {
  color: var(--text-faint);
}

.reg-count {
  display: block;
  font-size: 11px;
  color: var(--text-faint);
  margin-top: 2px;
}

/* ---- TICKETS ---- */
.col-tickets {
  font-size: 11px;
}

.ticket-on {
  display: block;
  color: var(--candle);
  font-size: 11px;
  font-weight: 500;
}

.ticket-detail {
  display: block;
  color: var(--text-faint);
  font-size: 10px;
  margin-top: 2px;
}

/* ---- ACTIONS ---- */
.col-actions-head {
  text-align: right;
}

.col-actions {
  text-align: right;
  white-space: nowrap;
}

.link-btn {
  background: none;
  border: none;
  color: var(--candle);
  cursor: pointer;
  font-family: 'Commit Mono', monospace;
  font-size: 11px;
  padding: 2px 6px;
  text-decoration: none;
}

.link-btn:hover {
  text-decoration: underline;
}

.link-btn-danger {
  color: var(--ember);
}

/* ---- STATES ---- */
.loading-state {
  text-align: center;
  padding: 48px 24px;
  color: var(--text-faint);
  font-size: 12px;
}

.error-state {
  text-align: center;
  padding: 48px 24px;
  color: var(--ember);
  font-size: 12px;
}

.empty-state {
  text-align: center;
  padding: 48px 24px;
  color: var(--text-faint);
  font-size: 12px;
}

.spinner {
  width: 24px;
  height: 24px;
  border: 2px dashed var(--candle);
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 12px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* ---- RESPONSIVE ---- */
@media (max-width: 768px) {
  .page-header {
    padding: 24px 20px 16px;
  }

  .header-row {
    flex-direction: column;
  }

  .filter-bar {
    flex-direction: column;
    padding: 12px 20px;
  }

  .table-wrap {
    padding: 0 12px 20px;
    overflow-x: auto;
  }

  table {
    min-width: 800px;
  }
}
</style>
