<template>
  <section class="system-admin-panel">
    <div class="th-section filter-section">
      <div class="th-section-header">
        <h2 class="th-section-title">{{ t('systemAdmin.audits.title') }}</h2>
        <button
          type="button"
          class="text-button"
          @click="resetFilters"
        >
          {{ t('workbench.reset') }}
        </button>
      </div>
      <div class="filter-grid">
        <label>
          <span>{{ t('systemAdmin.audits.targetType') }}</span>
          <input
            v-model="filters.target_type"
            type="search"
            @input="resetToFirstPage"
          >
        </label>
        <label>
          <span>{{ t('systemAdmin.audits.targetId') }}</span>
          <input
            v-model="filters.target_id"
            type="search"
            @input="resetToFirstPage"
          >
        </label>
        <label>
          <span>{{ t('systemAdmin.audits.action') }}</span>
          <input
            v-model="filters.action"
            type="search"
            @input="resetToFirstPage"
          >
        </label>
      </div>
    </div>

    <section class="th-section table-section">
      <div class="th-section-header">
        <div>
          <h2 class="th-section-title">{{ t('systemAdmin.audits.tableTitle') }}</h2>
          <p class="th-muted">{{ t('workbench.totalPrefix') }} {{ total }} {{ t('systemAdmin.audits.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="!audits.length"
        class="empty-state"
      >
        {{ t('common.noData') }}
      </div>
      <div
        v-else
        class="table-wrap"
      >
        <table>
          <thead>
            <tr>
              <th>{{ t('systemAdmin.audits.columns.action') }}</th>
              <th>{{ t('systemAdmin.audits.columns.target') }}</th>
              <th>{{ t('systemAdmin.audits.columns.actor') }}</th>
              <th>{{ t('systemAdmin.audits.columns.occurredAt') }}</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="audit in audits"
              :key="audit.id"
            >
              <td>
                <strong>{{ audit.action }}</strong>
                <small class="th-code">{{ audit.id }}</small>
              </td>
              <td>
                <strong>{{ audit.target_type }}</strong>
                <small class="th-code">{{ audit.target_id }}</small>
              </td>
              <td>
                <strong>{{ audit.actor_display_name || audit.actor_username }}</strong>
                <small class="th-code">{{ audit.actor_username }}</small>
              </td>
              <td>{{ formatReservationDateTime(audit.occurred_at) }}</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>
</template>

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

import { fetchAdminAudits } from '@/services/systemAdminService'
import type { AdminAuditLogListFilters, AdminAuditLogResult, PlatformPaginationResult } from '@/types/systemAdmin'
import { formatReservationDateTime } from '@/utils/reservationFormat'

const { t } = useI18n()
const loading = ref(false)
const errorMessage = ref('')
const audits = ref<AdminAuditLogResult[]>([])
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<AdminAuditLogListFilters>({
  target_type: '',
  target_id: '',
  action: '',
  page_num: 1,
  page_size: 20,
})
let requestSequence = 0

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

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

async function loadAudits(): Promise<void> {
  const currentRequest = ++requestSequence
  loading.value = true
  errorMessage.value = ''
  try {
    const result = await fetchAdminAudits({ ...filters })
    if (currentRequest !== requestSequence) {
      return
    }
    audits.value = result.items
    page.value = result.page
  } catch (error) {
    if (currentRequest !== requestSequence) {
      return
    }
    audits.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
    }
  }
}

function resetFilters(): void {
  filters.target_type = ''
  filters.target_id = ''
  filters.action = ''
  filters.page_num = 1
  filters.page_size = 20
}

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,
  }
}
</script>

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