<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="seriesFilter">
          <option value="all">All Events</option>
          <option value="series-only">Series Only</option>
          <option value="standalone-only">Standalone Only</option>
        </select>
      </div>
    </div>

    <!-- Loading / Error -->
    <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>

    <template v-else>
      <!-- ── Upcoming Events ── -->
      <div class="section-divider">
        <span class="section-label">Upcoming Events</span>
        <span class="event-count">{{ upcomingFiltered.length }}</span>
      </div>

      <div class="table-wrap">
        <table v-if="upcomingPaged.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 upcomingPaged" :key="event._id">
              <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>
              <td>
                <span class="badge" :class="event.eventType">{{ event.eventType }}</span>
              </td>
              <td class="col-date">
                <span class="date-main">{{ formatDate(event.startDate) }}</span>
                <span class="date-time">{{ formatTime(event.startDate) }}</span>
              </td>
              <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>
              <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>
              <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>
              <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 upcoming events matching your filters</div>

        <div v-if="upcomingPageCount > 1" class="pagination">
          <button class="page-btn" :disabled="upcomingPage === 1" @click="upcomingPage--">←</button>
          <span class="page-info">{{ upcomingPage }} / {{ upcomingPageCount }}</span>
          <button class="page-btn" :disabled="upcomingPage === upcomingPageCount" @click="upcomingPage++">→</button>
        </div>
      </div>

      <!-- ── Past Events ── -->
      <div class="section-divider">
        <span class="section-label">Past Events</span>
        <span class="event-count">{{ pastFiltered.length }}</span>
      </div>

      <div class="table-wrap">
        <table v-if="pastPaged.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 pastPaged" :key="event._id">
              <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>
              <td>
                <span class="badge" :class="event.eventType">{{ event.eventType }}</span>
              </td>
              <td class="col-date">
                <span class="date-main">{{ formatDate(event.startDate) }}</span>
                <span class="date-time">{{ formatTime(event.startDate) }}</span>
              </td>
              <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>
              <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>
              <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>
              <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 past events matching your filters</div>

        <div v-if="pastPageCount > 1" class="pagination">
          <button class="page-btn" :disabled="pastPage === 1" @click="pastPage--">←</button>
          <span class="page-info">{{ pastPage }} / {{ pastPageCount }}</span>
          <button class="page-btn" :disabled="pastPage === pastPageCount" @click="pastPage++">→</button>
        </div>
      </div>
    </template>

    <!-- Confirm Delete Modal -->
    <div v-if="confirmDelete.show" class="modal-overlay" @click.self="confirmDelete.show = false">
      <div class="modal">
        <div class="modal-header">
          <h2>Delete Event</h2>
          <button class="modal-close" @click="confirmDelete.show = false">&times;</button>
        </div>
        <div class="modal-body">
          <p>Are you sure you want to delete <strong>"{{ confirmDelete.title }}"</strong>?</p>
          <p class="help-text" style="margin-top: 8px;">This action cannot be undone.</p>
        </div>
        <div class="modal-actions">
          <button class="btn" @click="confirmDelete.show = false">Cancel</button>
          <button class="btn btn-danger" :disabled="confirmDelete.deleting" @click="executeDelete">
            {{ confirmDelete.deleting ? 'Deleting...' : 'Delete' }}
          </button>
        </div>
      </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 seriesFilter = ref('all')

const upcomingPage = ref(1)
const pastPage = ref(1)
const UPCOMING_PAGE_SIZE = 10
const PAST_PAGE_SIZE = 5

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 applyBaseFilters = (list) => {
  if (!list) return []
  return list.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 matchesSeries =
      seriesFilter.value === 'all' ||
      (seriesFilter.value === 'series-only' && event.series?.isSeriesEvent) ||
      (seriesFilter.value === 'standalone-only' && !event.series?.isSeriesEvent)

    return matchesSearch && matchesType && matchesSeries
  })
}

const upcomingFiltered = computed(() => {
  return applyBaseFilters(events.value)
    .filter((e) => getEventStatus(e) !== 'Past')
    .sort((a, b) => new Date(a.startDate) - new Date(b.startDate))
})

const pastFiltered = computed(() => {
  return applyBaseFilters(events.value)
    .filter((e) => getEventStatus(e) === 'Past')
    .sort((a, b) => new Date(b.startDate) - new Date(a.startDate))
})

const upcomingPageCount = computed(() => Math.max(1, Math.ceil(upcomingFiltered.value.length / UPCOMING_PAGE_SIZE)))
const pastPageCount = computed(() => Math.max(1, Math.ceil(pastFiltered.value.length / PAST_PAGE_SIZE)))

const upcomingPaged = computed(() => {
  const start = (upcomingPage.value - 1) * UPCOMING_PAGE_SIZE
  return upcomingFiltered.value.slice(start, start + UPCOMING_PAGE_SIZE)
})

const pastPaged = computed(() => {
  const start = (pastPage.value - 1) * PAST_PAGE_SIZE
  return pastFiltered.value.slice(start, start + PAST_PAGE_SIZE)
})

// Reset pagination when filters change
watch([searchQuery, typeFilter, seriesFilter], () => {
  upcomingPage.value = 1
  pastPage.value = 1
})

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 confirmDelete = reactive({ show: false, id: null, title: '', deleting: false })

const deleteEvent = (event) => {
  confirmDelete.id = String(event._id)
  confirmDelete.title = event.title
  confirmDelete.deleting = false
  confirmDelete.show = true
}

const executeDelete = async () => {
  confirmDelete.deleting = true
  try {
    await $fetch(`/api/admin/events/${confirmDelete.id}`, { method: 'DELETE' })
    confirmDelete.show = false
    await refresh()
  } catch (error) {
    console.error('Failed to delete event:', error)
  } finally {
    confirmDelete.deleting = false
  }
}

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 {}

/* ---- 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;
}

/* ---- SECTION DIVIDER ---- */
.section-divider {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 20px 28px 0;
}

.section-divider .section-label {
  font-size: 10px;
  letter-spacing: 0.1em;
  text-transform: uppercase;
  color: var(--text-faint);
  font-weight: normal;
}

.event-count {
  font-size: 10px;
  color: var(--text-faint);
  background: var(--surface);
  border: 1px dashed var(--border);
  padding: 1px 7px;
  letter-spacing: 0.04em;
}

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

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);
}

/* ---- PAGINATION ---- */
.pagination {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 14px 0 0;
}

.page-btn {
  background: none;
  border: 1px dashed var(--border);
  color: var(--candle);
  cursor: pointer;
  font-family: 'Commit Mono', monospace;
  font-size: 12px;
  padding: 3px 10px;
  transition: border-color 0.1s;
}

.page-btn:disabled {
  color: var(--text-faint);
  border-color: var(--border);
  cursor: default;
}

.page-btn:not(:disabled):hover {
  border-color: var(--candle);
}

.page-info {
  font-size: 11px;
  color: var(--text-faint);
  letter-spacing: 0.04em;
}

/* ---- 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: 32px 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); }
}

/* ---- MODALS ---- */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 50;
}

.modal {
  background: var(--bg);
  border: 1px dashed var(--border);
  max-width: 440px;
  width: 100%;
  margin: 16px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px 16px;
  border-bottom: 1px dashed var(--border);
}

.modal-header h2 {
  font-family: 'Brygada 1918', serif;
  font-size: 18px;
  font-weight: 500;
  color: var(--text-bright);
}

.modal-close {
  background: none;
  border: none;
  color: var(--text-faint);
  font-size: 20px;
  cursor: pointer;
  padding: 0 4px;
  line-height: 1;
}

.modal-close:hover {
  color: var(--text);
}

.modal-body {
  padding: 20px 24px;
}

.modal-body p {
  font-size: 13px;
  color: var(--text);
  line-height: 1.5;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 16px 24px;
  border-top: 1px dashed var(--border);
}

.help-text {
  font-size: 11px;
  color: var(--text-dim);
}

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

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

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

  .section-divider {
    padding: 16px 20px 0;
  }

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

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