<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue'
import { useAdminOrders } from '@/composables/useAdminOrders'
import { useAdminOrderActions } from '@/composables/useAdminOrderActions'
import AdminStatsBar from '@/components/admin/AdminStatsBar.vue'
import AdminOrdersTable from '@/components/admin/AdminOrdersTable.vue'
import AdminOrderMessageModal from '@/components/admin/AdminOrderMessageModal.vue'

const {
  orders,
  loading,
  error,
  activeFilter,
  searchQuery,
  stats,
  filteredOrders,
  loadOrders,
  replaceOrder,
} = useAdminOrders()

const {
  expandedOrderId,
  statusError,
  trackingError,
  notesError,
  savingNotesId,
  registeringId,
  messageModalOrder,
  trackingInputValues,
  adminNotesValues,
  notifyCustomerValues,
  openMessageModal,
  closeMessageModal,
  toggleExpand,
  handleStatusChange,
  handleRegisterShipment,
  handleNotesSave,
} = useAdminOrderActions(orders, replaceOrder)

const umamiDashboardUrl = import.meta.env.VITE_UMAMI_WEBSITE_ID
  ? 'https://analytics.bilhej.se'
  : null

function handleModalKeydown(event: KeyboardEvent) {
  if (event.key === 'Escape' && messageModalOrder.value) {
    closeMessageModal()
  }
}

onMounted(() => {
  window.addEventListener('keydown', handleModalKeydown)
  void loadOrders()
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleModalKeydown)
})
</script>

<template>
  <div class="admin">
    <header class="admin__header">
      <h1 class="admin__title">Administration</h1>
      <a
        v-if="umamiDashboardUrl"
        class="admin__analytics-link"
        :href="umamiDashboardUrl"
        target="_blank"
        rel="noopener noreferrer"
      >
        Webbstatistik
      </a>
    </header>

    <p
      v-if="loading"
      class="text-muted text-center admin__loading"
      role="status"
    >
      Laddar beställningar...
    </p>

    <div v-else-if="error" class="message message--error">{{ error }}</div>

    <div v-else-if="orders.length === 0" class="message message--info">
      Inga beställningar ännu.
    </div>

    <template v-else>
      <AdminStatsBar
        v-model:active-filter="activeFilter"
        v-model:search-query="searchQuery"
        :total="stats.total"
        :todo="stats.todo"
        :paid="stats.paid"
        :pending="stats.pending"
      />

      <p
        v-if="filteredOrders.length === 0"
        class="message message--info admin__filter-empty"
      >
        Inga beställningar matchar filtret.
      </p>

      <AdminOrdersTable
        v-if="filteredOrders.length > 0"
        :orders="filteredOrders"
        :expanded-order-id="expandedOrderId"
        :status-error="statusError"
        :tracking-error="trackingError"
        :notes-error="notesError"
        :tracking-input-values="trackingInputValues"
        :admin-notes-values="adminNotesValues"
        :notify-customer-values="notifyCustomerValues"
        :saving-notes-id="savingNotesId"
        :registering-id="registeringId"
        @toggle-expand="toggleExpand"
        @open-message="openMessageModal"
        @status-change="handleStatusChange"
        @register-shipment="handleRegisterShipment"
        @save-notes="handleNotesSave"
        @update:tracking-input="
          (id, value) => {
            trackingInputValues[id] = value
          }
        "
        @update:admin-notes="
          (id, value) => {
            adminNotesValues[id] = value
          }
        "
        @update:notify-customer="
          (id, value) => {
            notifyCustomerValues[id] = value
          }
        "
      />
    </template>

    <AdminOrderMessageModal
      :order="messageModalOrder"
      @close="closeMessageModal"
    />
  </div>
</template>

<style scoped>
.admin {
  max-width: 72rem;
  margin: var(--space-2xl) auto 0;
  padding: 0 var(--space-lg);
}

.admin__header {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-md);
  margin-bottom: var(--space-xl);
}

.admin__title {
  margin: 0;
  font-size: 1.5rem;
  color: var(--color-ink);
}

.admin__analytics-link {
  font-size: 0.875rem;
  font-weight: 600;
  color: var(--color-primary);
  text-decoration: underline;
  text-underline-offset: 2px;
}

.admin__analytics-link:hover {
  color: var(--color-primary-dark);
}

.admin__stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: var(--space-md);
  margin-bottom: var(--space-xl);
}

.admin__stat {
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-lg);
  padding: var(--space-md) var(--space-lg);
  text-align: center;
  box-shadow: var(--shadow-sm);
  cursor: pointer;
  font: inherit;
  width: 100%;
  transition:
    border-color var(--transition-fast),
    background var(--transition-fast);
}

.admin__stat:hover {
  border-color: var(--color-primary);
}

.admin__stat--active {
  background: var(--color-primary-soft);
  border-color: var(--color-primary);
}

.admin__toolbar {
  margin-bottom: var(--space-lg);
}

.admin__search-label {
  display: block;
  font-size: 0.75rem;
  font-weight: 600;
  color: var(--color-muted);
  text-transform: uppercase;
  letter-spacing: 0.05em;
  margin-bottom: var(--space-xs);
}

.admin__search-input {
  width: 100%;
  max-width: 24rem;
  padding: 0.5rem 0.75rem;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  font-size: 0.875rem;
  color: var(--color-ink);
  outline: none;
  transition: border-color var(--transition-fast);
}

.admin__search-input:focus {
  border-color: var(--color-primary);
  box-shadow: 0 0 0 2px var(--color-primary-ring);
}

.admin__filter-empty {
  margin-bottom: var(--space-md);
}

.admin__order-id {
  font-family: ui-monospace, monospace;
  font-size: 0.8125rem;
}

.admin__message-btn {
  white-space: nowrap;
}

.admin__stat-value {
  display: block;
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--color-ink);
}

.admin__stat-label {
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  color: var(--color-muted);
  margin-top: var(--space-xs);
}

.admin__table-wrap {
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-card);
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.admin__table {
  width: 100%;
  min-width: 60rem;
  border-collapse: separate;
  border-spacing: 0;
  font-size: 0.875rem;
}

.admin__table thead {
  background: var(--color-border-light);
}

.admin__table th {
  padding: 0.75rem 1rem;
  text-align: left;
  font-size: 0.75rem;
  font-weight: 600;
  color: var(--color-muted);
  text-transform: uppercase;
  letter-spacing: 0.05em;
  border-bottom: 1px solid var(--color-border);
  white-space: nowrap;
}

.admin__th-expand,
.admin__expand-cell {
  width: 2.75rem;
  padding-left: 0.75rem;
  padding-right: 0.25rem;
}

.admin__expand-cell {
  text-align: center;
  vertical-align: middle;
}

.admin__expand-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 1.625rem;
  height: 1.625rem;
  border-radius: var(--radius-full);
  background: var(--color-border-light);
  color: var(--color-muted);
  transition:
    background var(--transition-fast),
    color var(--transition-fast);
}

.admin__row:hover .admin__expand-icon {
  background: var(--color-primary-soft);
  color: var(--color-primary);
}

.admin__row--expanded .admin__expand-icon,
.admin__expand-icon--open {
  background: var(--color-primary);
  color: #fff;
}

.admin__row--todo .admin__expand-icon:not(.admin__expand-icon--open) {
  background: var(--color-primary-soft);
  color: var(--color-primary);
}

.admin__th-date,
.admin__td-date {
  min-width: 6.5rem;
}

.admin__th-id,
.admin__order-id {
  min-width: 5.5rem;
}

.admin__th-email,
.admin__email {
  min-width: 11rem;
  max-width: 16rem;
}

.admin__th-plate,
.admin__plate {
  min-width: 5rem;
}

.admin__th-message,
.admin__message-cell {
  min-width: 9.5rem;
}

.admin__th-status,
.admin__status-cell {
  min-width: 11rem;
}

.admin__row {
  cursor: pointer;
  transition: background var(--transition-fast);
}

.admin__row:last-child td {
  border-bottom: none;
}

.admin__row:hover {
  background: var(--color-border-light);
}

.admin__row--expanded {
  background: var(--color-primary-soft) !important;
}

.admin__row--todo {
  border-left: 3px solid var(--color-primary);
}

.admin__row td {
  padding: 0.75rem 1rem;
  color: var(--color-ink);
  vertical-align: middle;
  border-bottom: 1px solid var(--color-border-light);
}

.admin__email {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 0.8125rem;
  color: var(--color-muted);
}

.admin__plate {
  font-weight: 600;
  letter-spacing: 0.05em;
  white-space: nowrap;
}

.admin__message-cell {
  text-align: center;
}

.admin__status-cell {
  white-space: nowrap;
}

.admin__status-select {
  padding: 0.2rem 0.5rem;
  border-radius: var(--radius-sm);
  border: 1px solid var(--color-border);
  font-size: 0.75rem;
  font-weight: 600;
  color: var(--color-ink);
  outline: none;
  cursor: pointer;
  background: var(--color-surface);
}

.admin__status-select:focus {
  border-color: var(--color-primary);
  box-shadow: 0 0 0 2px var(--color-primary-ring);
}

.admin__expanded-row td {
  padding: 0;
  background: var(--color-surface);
}

.admin__expanded-inner {
  padding: var(--space-lg);
  display: flex;
  flex-direction: column;
  gap: var(--space-lg);
  border-top: 1px solid var(--color-border-light);
}

.admin__section {
  padding: var(--space-md);
  background: var(--color-border-light);
  border-radius: var(--radius-md);
}

.admin__section-label {
  font-size: 0.75rem;
  font-weight: 600;
  color: var(--color-muted);
  text-transform: uppercase;
  letter-spacing: 0.05em;
  margin-bottom: var(--space-sm);
}

.admin__section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.admin__tracking-link {
  font-size: 0.8125rem;
  color: var(--color-primary);
  text-decoration: none;
  font-weight: 500;
}

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

.admin__tracking-row {
  display: flex;
  gap: var(--space-sm);
  margin-top: var(--space-sm);
}

.admin__tracking-input {
  flex: 1;
  padding: 0.5rem 0.75rem;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  font-size: 0.8125rem;
  color: var(--color-ink);
  outline: none;
  transition: border-color var(--transition-fast);
}

.admin__tracking-input:focus {
  border-color: var(--color-primary);
  box-shadow: 0 0 0 2px var(--color-primary-ring);
}

.admin__loading {
  padding: var(--space-2xl) 0;
}

.admin__status-error {
  margin-bottom: var(--space-md);
}

.admin__checklist {
  margin: 0 0 var(--space-md);
  padding-left: 1.25rem;
  font-size: 0.875rem;
  color: var(--color-ink-muted);
}

.admin__checklist li + li {
  margin-top: var(--space-xs);
}

.admin__section-hint {
  margin: var(--space-xs) 0 0;
  font-size: 0.8125rem;
  color: var(--color-ink-muted);
}

.admin__notify {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  margin-top: var(--space-sm);
  font-size: 0.8125rem;
  color: var(--color-ink-muted);
  cursor: pointer;
}

.admin__notes-input {
  width: 100%;
  margin-top: var(--space-sm);
  padding: 0.5rem 0.75rem;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  font-size: 0.8125rem;
  font-family: inherit;
  resize: vertical;
}

.admin__notes-save {
  margin-top: var(--space-sm);
}

.admin__tracking-error {
  margin-bottom: var(--space-sm);
  padding: var(--space-sm) var(--space-md);
  font-size: 0.8125rem;
}

.admin-modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: var(--space-md);
}

.admin-modal {
  background: var(--color-surface);
  border-radius: var(--radius-xl);
  width: 100%;
  max-width: 32rem;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  box-shadow: var(--shadow-card);
  border: 1px solid var(--color-border);
}

.admin-modal__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--space-lg) var(--space-lg) 0;
}

.admin-modal__title {
  margin: 0;
  font-size: 1.125rem;
  color: var(--color-ink);
}

.admin-modal__close {
  background: none;
  border: none;
  color: var(--color-muted);
  cursor: pointer;
  padding: 0.25rem;
  border-radius: var(--radius-sm);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition:
    color var(--transition-fast),
    background var(--transition-fast);
}

.admin-modal__close:hover {
  color: var(--color-ink);
  background: var(--color-border-light);
}

.admin-modal__meta {
  margin: var(--space-sm) var(--space-lg) 0;
  font-size: 0.8125rem;
  color: var(--color-muted);
  font-family: ui-monospace, monospace;
}

.admin-modal__body {
  margin: var(--space-md) var(--space-lg) var(--space-lg);
  padding: var(--space-md);
  background: var(--color-border-light);
  border-radius: var(--radius-md);
  font-size: 0.875rem;
  color: var(--color-ink);
  line-height: 1.6;
  white-space: pre-wrap;
  overflow-y: auto;
  max-height: 60vh;
}

@media (max-width: 768px) {
  .admin__stats {
    grid-template-columns: repeat(2, 1fr);
  }

  .admin__table {
    min-width: 62rem;
  }

  .admin__message-btn {
    font-size: 0.75rem;
    padding-inline: 0.5rem;
  }
}
</style>
