<template>
  <div class="th-page list-view">
    <header class="page-heading">
      <div>
        <h1>{{ t('orderList.title') }}</h1>
        <p>{{ t('orderList.subtitle') }}</p>
      </div>
    </header>

    <section class="th-section filter-section">
      <div class="th-section-header">
        <h2 class="th-section-title">
          {{ t('workbench.filters') }}
        </h2>
        <button
          type="button"
          class="text-button"
          @click="resetFilters"
        >
          {{ t('workbench.reset') }}
        </button>
      </div>
      <div class="filter-grid">
        <label>
          <span>{{ t('orderList.keyword') }}</span>
          <input
            v-model="filters.keyword"
            type="search"
            :placeholder="t('orderList.keywordPlaceholder')"
            @input="resetToFirstPage"
          >
        </label>
        <label>
          <span>{{ t('workbench.orderStatus') }}</span>
          <select
            v-model="filters.order_status"
            name="order_status"
            @change="resetToFirstPage"
          >
            <option value="">{{ t('common.all') }}</option>
            <option value="TEMPORARY">{{ t('status.TEMPORARY') }}</option>
            <option value="ACTIVE">{{ t('status.ACTIVE') }}</option>
            <option value="ENDED">{{ t('status.ENDED') }}</option>
            <option value="LOGIC_DELETED">{{ t('status.LOGIC_DELETED') }}</option>
          </select>
        </label>
        <label>
          <span>{{ t('orderList.groupCode') }}</span>
          <input
            v-model="filters.group_code"
            name="group_code"
            type="search"
            :placeholder="t('orderList.groupCodePlaceholder')"
            @input="resetToFirstPage"
          >
        </label>
        <label>
          <span>{{ t('orderList.confirmationNumber') }}</span>
          <input
            v-model="filters.confirmation_number"
            name="confirmation_number"
            type="search"
            :placeholder="t('orderList.confirmationNumberPlaceholder')"
            @input="resetToFirstPage"
          >
        </label>
      </div>
    </section>

    <section class="th-section table-section">
      <div class="th-section-header">
        <div>
          <h2 class="th-section-title">
            {{ t('orderList.tableTitle') }}
          </h2>
          <p class="th-muted">
            {{ t('workbench.totalPrefix') }} {{ total }} {{ t('orderList.totalSuffix') }}
          </p>
        </div>
      </div>

      <div
        v-if="loading"
        class="empty-state"
      >
        {{ t('common.loading') }}
      </div>

      <div
        v-else-if="errorMessage"
        class="empty-state empty-state--error"
      >
        {{ errorMessage }}
      </div>

      <div
        v-else-if="!orders.length"
        class="empty-state"
      >
        {{ t('common.noData') }}
      </div>

      <div
        v-else
        class="table-wrap"
      >
        <table>
          <thead>
            <tr>
              <th>{{ t('orderList.columns.order') }}</th>
              <th>{{ t('orderList.columns.status') }}</th>
              <th>{{ t('orderList.columns.openTasks') }}</th>
              <th>{{ t('orderList.columns.createdAt') }}</th>
              <th>{{ t('workbench.columns.updatedAt') }}</th>
              <th>{{ t('workbench.columns.operation') }}</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="order in orders"
              :key="order.order_id"
            >
              <td>
                <strong>{{ formatOrderKey(order) }}</strong>
                <small class="th-code">{{ order.order_id }}</small>
              </td>
              <td><ReservationStatusBadge :status="order.order_status" /></td>
              <td>{{ order.open_task_count ?? 0 }}</td>
              <td>{{ formatReservationDateTime(order.created_at) }}</td>
              <td>{{ formatReservationDateTime(order.updated_at) }}</td>
              <td>
                <div class="row-actions">
                  <RouterLink
                    class="row-action"
                    :to="`/reservation/orders/${order.order_id}`"
                  >
                    {{ t('orderList.viewDetail') }}
                  </RouterLink>
                  <RouterLink
                    v-if="order.next_processable_task_id"
                    class="row-action"
                    :to="`/reservation/tasks/${order.next_processable_task_id}`"
                  >
                    {{ t('orderList.continueTask') }}
                  </RouterLink>
                  <span
                    v-else
                    class="row-action row-action--muted"
                  >
                    {{ t('orderList.noOpenTask') }}
                  </span>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <footer class="pagination-bar">
        <label class="page-size-control">
          <span>{{ t('common.pageSize') }}</span>
          <select
            v-model.number="filters.page_size"
            @change="resetToFirstPage"
          >
            <option :value="10">10</option>
            <option :value="20">20</option>
            <option :value="50">50</option>
          </select>
        </label>
        <div class="pagination-actions">
          <button
            type="button"
            class="secondary-button"
            :disabled="currentPage <= 1 || loading"
            @click="goToPage(currentPage - 1)"
          >
            {{ t('common.previousPage') }}
          </button>
          <span>{{ t('common.pageStatus', { current: currentPage, total: totalPages }) }}</span>
          <button
            type="button"
            class="secondary-button"
            :disabled="currentPage >= totalPages || loading"
            @click="goToPage(currentPage + 1)"
          >
            {{ t('common.nextPage') }}
          </button>
        </div>
      </footer>
    </section>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { RouterLink } from 'vue-router'
import { useI18n } from 'vue-i18n'

import ReservationStatusBadge from '@/components/reservation/ReservationStatusBadge.vue'
import { fetchReservationOrders } from '@/services/reservationService'
import { useAuthStore } from '@/stores/authStore'
import type { ReservationOrderListFilters, ReservationOrderListItem, ReservationPageResult } from '@/types/reservation'
import { formatReservationDateTime } from '@/utils/reservationFormat'

const { t } = useI18n()
const authStore = useAuthStore()
const loading = ref(false)
const errorMessage = ref('')
const orders = ref<ReservationOrderListItem[]>([])
const page = ref(createPage(1, 20, 0))
const total = computed(() => page.value.total)
const currentPage = computed(() => page.value.page_num)
const totalPages = computed(() => Math.max(1, Math.ceil(page.value.total / Math.max(page.value.page_size, 1))))
let orderListRequestSequence = 0
const filters = reactive<ReservationOrderListFilters>({
  keyword: '',
  order_status: '',
  group_code: '',
  confirmation_number: '',
  page_num: 1,
  page_size: 20,
})

onMounted(() => {
  void loadOrders()
})

watch(filters, () => {
  void loadOrders()
})

watch(
  () => authStore.selectedHotelId,
  (nextHotelId, previousHotelId) => {
    if (!nextHotelId || nextHotelId === previousHotelId) {
      return
    }
    reloadOrdersForHotelChange()
  },
)

async function loadOrders(): Promise<void> {
  const requestSequence = ++orderListRequestSequence
  loading.value = true
  errorMessage.value = ''
  try {
    const result = await fetchReservationOrders({ ...filters })
    if (requestSequence !== orderListRequestSequence) {
      return
    }
    orders.value = result.items
    page.value = result.page
  } catch (error) {
    if (requestSequence !== orderListRequestSequence) {
      return
    }
    orders.value = []
    page.value = createPage(filters.page_num ?? 1, filters.page_size ?? 20, 0)
    errorMessage.value = error instanceof Error ? error.message : String(error)
  } finally {
    if (requestSequence === orderListRequestSequence) {
      loading.value = false
    }
  }
}

function resetFilters(): void {
  filters.keyword = ''
  filters.order_status = ''
  filters.group_code = ''
  filters.confirmation_number = ''
  filters.page_num = 1
  filters.page_size = 20
}

function resetToFirstPage(): void {
  filters.page_num = 1
}

function reloadOrdersForHotelChange(): void {
  if (filters.page_num !== 1) {
    filters.page_num = 1
    return
  }
  void loadOrders()
}

function goToPage(page: number): void {
  filters.page_num = Math.min(Math.max(page, 1), totalPages.value)
}

function createPage(pageNum: number, pageSize: number, total: number): ReservationPageResult {
  return {
    page_num: pageNum,
    page_size: pageSize,
    total,
  }
}

function formatOrderKey(order: ReservationOrderListItem): string {
  return (
    order.display_order_key ??
    order.group_code ??
    order.confirmation_number ??
    order.temporary_order_no ??
    order.display_name ??
    order.order_id
  )
}
</script>

<style scoped>
.list-view {
  max-width: 1280px;
}

.page-heading h1,
.page-heading p {
  margin: 0;
}

.page-heading h1 {
  color: var(--th-color-slate-900);
  font-size: 28px;
}

.page-heading p {
  margin-top: 8px;
  color: var(--th-color-slate-500);
  font-size: 14px;
}

.filter-section {
  padding-bottom: 20px;
}

.filter-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 14px;
  padding: 18px 20px 0;
}

.filter-grid label {
  display: grid;
  gap: 7px;
}

.filter-grid span {
  color: var(--th-color-slate-500);
  font-size: 12px;
  font-weight: 700;
}

.filter-grid input,
.filter-grid select {
  min-height: 38px;
  min-width: 0;
  border: 1px solid var(--th-color-slate-200);
  border-radius: var(--th-radius-sm);
  background: var(--th-color-white);
  color: var(--th-color-slate-900);
  padding: 8px 10px;
}

.text-button,
.row-action {
  border: 0;
  background: transparent;
  color: var(--th-color-blue-600);
  cursor: pointer;
  font-size: 13px;
  font-weight: 800;
  text-decoration: none;
}

.row-action--muted {
  color: var(--th-color-slate-500);
  cursor: default;
}

.empty-state {
  min-height: 220px;
  display: grid;
  place-items: center;
  gap: 8px;
  color: var(--th-color-slate-500);
  font-size: 13px;
  padding: 24px;
  text-align: center;
}

.empty-state strong {
  color: var(--th-color-slate-900);
}

.empty-state--error {
  color: var(--th-color-danger);
}

.table-section {
  overflow: hidden;
}

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

table {
  width: 100%;
  min-width: 920px;
  border-collapse: collapse;
}

th,
td {
  border-bottom: 1px solid var(--th-color-slate-200);
  padding: 14px 10px;
  text-align: left;
  vertical-align: middle;
}

th {
  color: var(--th-color-slate-500);
  font-size: 12px;
  font-weight: 800;
}

td {
  color: var(--th-color-slate-900);
  font-size: 13px;
}

td strong,
td small {
  display: block;
}

td small {
  margin-top: 4px;
  color: var(--th-color-slate-500);
  font-size: 12px;
}

.row-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 14px;
  border-top: 1px solid var(--th-color-slate-200);
  padding: 14px 20px 18px;
}

.page-size-control,
.pagination-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-size-control span,
.pagination-actions span {
  color: var(--th-color-slate-500);
  font-size: 12px;
  font-weight: 800;
}

.page-size-control select {
  min-height: 34px;
  border: 1px solid var(--th-color-slate-200);
  border-radius: var(--th-radius-sm);
  background: var(--th-color-white);
  color: var(--th-color-slate-900);
  padding: 6px 8px;
}

.secondary-button {
  min-height: 34px;
  border: 1px solid var(--th-color-slate-200);
  border-radius: var(--th-radius-sm);
  background: var(--th-color-white);
  color: var(--th-color-slate-700);
  cursor: pointer;
  font-size: 12px;
  font-weight: 800;
  padding: 6px 12px;
}

.secondary-button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

@media (max-width: 720px) {
  .filter-grid {
    grid-template-columns: 1fr;
  }

  .pagination-bar {
    align-items: flex-start;
    flex-direction: column;
  }
}
</style>
