<template>
  <div class="page">
    <PageHeader :title="t('requestIPs.title')" :description="t('requestIPs.description')">
      <template #actions>
        <el-button @click="load">{{ t('common.refresh') }}</el-button>
      </template>
    </PageHeader>

    <AppCard>
      <div class="card-toolbar">
        <el-input v-model="query" :placeholder="t('requestIPs.searchPlaceholder')" clearable class="toolbar-input" @keyup.enter="search" @clear="search" />
        <el-button @click="search">{{ t('common.search') }}</el-button>
      </div>
      <el-table :data="list" v-loading="loading" size="small">
        <el-table-column prop="ip" :label="t('dashboard.visitorIp')" min-width="140" />
        <el-table-column prop="resource_label" :label="t('common.resource')" min-width="160" show-overflow-tooltip />
        <el-table-column prop="hit_count" :label="t('requestIPs.hitCount')" width="100" />
        <el-table-column :label="t('requestIPs.lastSeen')" min-width="160">
          <template #default="{ row }">{{ row.last_seen_at }}</template>
        </el-table-column>
        <el-table-column :label="t('common.actions')" width="120" fixed="right">
          <template #default="{ row }">
            <el-button size="small" link type="danger" @click="block(row)">{{ t('common.block') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="card-pager">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          @current-change="load"
        />
      </div>
    </AppCard>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageHeader from '@/components/PageHeader.vue'
import AppCard from '@/components/AppCard.vue'
import api from '@/api'

const { t } = useI18n()
const list = ref([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(50)
const total = ref(0)
const query = ref('')

async function load() {
  loading.value = true
  try {
    const { data } = await api.get('/security/request-ips', {
      params: { limit: pageSize.value, offset: (page.value - 1) * pageSize.value, q: query.value || undefined },
    })
    list.value = data.items || []
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

function search() {
  page.value = 1
  load()
}

async function block(row) {
  await ElMessageBox.confirm(t('requestIPs.confirmBlock'), t('common.hint'), { type: 'warning' })
  await api.post('/security/block-ip', {
    ip: row.ip,
    scope: row.resource_type,
    resource_id: row.resource_id,
  })
  ElMessage.success(t('message.blockSuccess'))
  load()
}

onMounted(load)
</script>
