<template>
  <section class="system-admin-panel">
    <div class="th-section filter-section">
      <div class="th-section-header">
        <h2 class="th-section-title">{{ t('systemAdmin.hotels.title') }}</h2>
        <button
          type="button"
          class="text-button"
          @click="resetFilters"
        >
          {{ t('workbench.reset') }}
        </button>
      </div>
      <div class="filter-grid">
        <label>
          <span>{{ t('systemAdmin.common.keyword') }}</span>
          <input
            v-model="filters.keyword"
            type="search"
            :placeholder="t('systemAdmin.hotels.keywordPlaceholder')"
            @input="resetToFirstPage"
          >
        </label>
        <label>
          <span>{{ t('systemAdmin.hotels.hotelStatus') }}</span>
          <select
            v-model="filters.hotel_status"
            @change="resetToFirstPage"
          >
            <option value="">{{ t('common.all') }}</option>
            <option value="ACTIVE">{{ t('systemAdmin.status.ACTIVE') }}</option>
            <option value="DISABLED">{{ t('systemAdmin.status.DISABLED') }}</option>
          </select>
        </label>
      </div>
    </div>

    <section class="th-section action-section">
      <div class="th-section-header">
        <h2 class="th-section-title">{{ t('systemAdmin.hotels.createTitle') }}</h2>
      </div>
      <form
        class="form-grid"
        @submit.prevent="createHotel"
      >
        <label>
          <span>{{ t('systemAdmin.hotels.hotelId') }}</span>
          <input
            v-model="createForm.hotel_id"
            type="text"
          >
        </label>
        <label>
          <span>{{ t('systemAdmin.hotels.hotelName') }}</span>
          <input
            v-model="createForm.hotel_name"
            type="text"
          >
        </label>
        <label>
          <span>{{ t('systemAdmin.hotels.columns.timeZone') }}</span>
          <input
            v-model="createForm.time_zone"
            type="text"
          >
        </label>
        <label>
          <span>{{ t('systemAdmin.hotels.columns.sort') }}</span>
          <input
            v-model.number="createForm.sort_order"
            type="number"
          >
        </label>
        <button
          type="submit"
          class="primary-button"
          :disabled="saving"
        >
          {{ t('systemAdmin.common.create') }}
        </button>
      </form>
    </section>

    <section class="th-section table-section">
      <div class="th-section-header">
        <div>
          <h2 class="th-section-title">{{ t('systemAdmin.hotels.tableTitle') }}</h2>
          <p class="th-muted">{{ t('workbench.totalPrefix') }} {{ total }} {{ t('systemAdmin.hotels.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="!hotels.length"
        class="empty-state"
      >
        {{ t('common.noData') }}
      </div>
      <div
        v-else
        class="table-wrap"
      >
        <table>
          <thead>
            <tr>
              <th>{{ t('systemAdmin.hotels.columns.hotel') }}</th>
              <th>{{ t('systemAdmin.hotels.columns.status') }}</th>
              <th>{{ t('systemAdmin.hotels.columns.timeZone') }}</th>
              <th>{{ t('systemAdmin.hotels.columns.authorizedUsers') }}</th>
              <th>{{ t('systemAdmin.hotels.columns.sort') }}</th>
              <th>{{ t('workbench.columns.updatedAt') }}</th>
              <th>{{ t('workbench.columns.operation') }}</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="hotel in hotels"
              :key="hotel.id"
            >
              <td>
                <strong>{{ hotel.hotel_name }}</strong>
                <small class="th-code">{{ hotel.hotel_id }}</small>
              </td>
              <td><span class="status-pill">{{ statusLabel(hotel.hotel_status) }}</span></td>
              <td>{{ hotel.time_zone }}</td>
              <td>{{ hotel.authorized_user_count }}</td>
              <td>{{ hotel.sort_order ?? '-' }}</td>
              <td>{{ formatReservationDateTime(hotel.updated_at) }}</td>
              <td>
                <button
                  type="button"
                  class="row-action"
                  @click="selectHotel(hotel)"
                >
                  {{ t('systemAdmin.common.edit') }}
                </button>
              </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>

    <section
      v-if="selectedHotel"
      class="th-section action-section"
    >
      <div class="th-section-header">
        <h2 class="th-section-title">{{ t('systemAdmin.hotels.editTitle') }}</h2>
        <span class="th-code">{{ selectedHotel.hotel_id }}</span>
      </div>
      <form
        class="form-grid"
        @submit.prevent="updateSelectedHotel"
      >
        <label>
          <span>{{ t('systemAdmin.hotels.hotelName') }}</span>
          <input
            v-model="editForm.hotel_name"
            type="text"
          >
        </label>
        <label>
          <span>{{ t('systemAdmin.hotels.columns.timeZone') }}</span>
          <input
            v-model="editForm.time_zone"
            type="text"
          >
        </label>
        <label>
          <span>{{ t('systemAdmin.hotels.columns.sort') }}</span>
          <input
            v-model.number="editForm.sort_order"
            type="number"
          >
        </label>
        <label>
          <span>{{ t('systemAdmin.hotels.hotelStatus') }}</span>
          <select v-model="statusForm.hotel_status">
            <option value="ACTIVE">{{ t('systemAdmin.status.ACTIVE') }}</option>
            <option value="DISABLED">{{ t('systemAdmin.status.DISABLED') }}</option>
          </select>
        </label>
        <button
          type="submit"
          class="primary-button"
          :disabled="saving"
        >
          {{ t('systemAdmin.common.save') }}
        </button>
        <button
          type="button"
          class="secondary-button"
          :disabled="saving"
          @click="updateSelectedHotelStatus"
        >
          {{ t('systemAdmin.hotels.saveStatus') }}
        </button>
      </form>
      <p class="form-message">
        {{ t('systemAdmin.hotels.singleActiveRule') }}
      </p>
    </section>
  </section>
</template>

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

import {
  createAdminHotel,
  fetchAdminHotels,
  updateAdminHotel,
  updateAdminHotelStatus,
} from '@/services/systemAdminService'
import type {
  AdminHotelCreateRequest,
  AdminHotelListFilters,
  AdminHotelResult,
  AdminHotelStatusUpdateRequest,
  AdminHotelUpdateRequest,
  PlatformPaginationResult,
} from '@/types/systemAdmin'
import { formatReservationDateTime } from '@/utils/reservationFormat'

const { t } = useI18n()
const loading = ref(false)
const errorMessage = ref('')
const saving = ref(false)
const hotels = ref<AdminHotelResult[]>([])
const selectedHotel = ref<AdminHotelResult | null>(null)
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))))
const filters = reactive<AdminHotelListFilters>({
  keyword: '',
  hotel_status: '',
  page_num: 1,
  page_size: 20,
})
const createForm = reactive<AdminHotelCreateRequest>({
  hotel_id: '',
  hotel_name: '',
  time_zone: 'Asia/Bangkok',
  sort_order: 100,
})
const editForm = reactive<AdminHotelUpdateRequest>({
  hotel_name: '',
  time_zone: 'Asia/Bangkok',
  sort_order: 0,
})
const statusForm = reactive<AdminHotelStatusUpdateRequest>({
  hotel_status: 'DISABLED',
})
let requestSequence = 0

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

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

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

async function createHotel(): Promise<void> {
  saving.value = true
  errorMessage.value = ''
  try {
    const result = await createAdminHotel({ ...createForm })
    resetCreateForm()
    await loadHotels()
    selectHotel(result)
  } catch (error) {
    setOperationError(error)
  } finally {
    saving.value = false
  }
}

async function updateSelectedHotel(): Promise<void> {
  if (!selectedHotel.value) {
    return
  }
  saving.value = true
  errorMessage.value = ''
  try {
    const result = await updateAdminHotel(selectedHotel.value.hotel_id, { ...editForm })
    selectedHotel.value = result
    populateEditForm(result)
    await loadHotels()
  } catch (error) {
    setOperationError(error)
  } finally {
    saving.value = false
  }
}

async function updateSelectedHotelStatus(): Promise<void> {
  if (!selectedHotel.value) {
    return
  }
  saving.value = true
  errorMessage.value = ''
  try {
    const result = await updateAdminHotelStatus(selectedHotel.value.hotel_id, { ...statusForm })
    selectedHotel.value = result
    populateEditForm(result)
    await loadHotels()
  } catch (error) {
    setOperationError(error)
  } finally {
    saving.value = false
  }
}

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

function resetCreateForm(): void {
  createForm.hotel_id = ''
  createForm.hotel_name = ''
  createForm.time_zone = 'Asia/Bangkok'
  createForm.sort_order = 100
}

function selectHotel(hotel: AdminHotelResult): void {
  selectedHotel.value = hotel
  populateEditForm(hotel)
}

function populateEditForm(hotel: AdminHotelResult): void {
  editForm.hotel_name = hotel.hotel_name
  editForm.time_zone = hotel.time_zone
  editForm.sort_order = hotel.sort_order ?? 0
  statusForm.hotel_status = hotel.hotel_status
}

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

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

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

function statusLabel(status: string): string {
  return t(`systemAdmin.status.${status}`)
}

function setOperationError(error: unknown): void {
  errorMessage.value = error instanceof Error ? error.message : String(error)
}
</script>

<style scoped>
@import './system-admin.css';
</style>
