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

    <AppCard>
      <el-table :data="list" v-loading="loading" size="small">
        <el-table-column prop="id" :label="t('common.id')" width="60" />
        <el-table-column prop="username" :label="t('users.username')" min-width="120" />
        <el-table-column :label="t('common.status')" width="88">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'info'" size="small">{{ row.status ? t('common.enabled') : t('common.disabled') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="t('common.actions')" width="220" fixed="right">
          <template #default="{ row }">
            <el-button size="small" link type="primary" @click="openLogs(row)">{{ t('users.accessLogs') }}</el-button>
            <el-button size="small" link type="primary" @click="openDialog(row)">{{ t('common.edit') }}</el-button>
            <el-button size="small" link type="danger" @click="remove(row)">{{ t('common.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </AppCard>

    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? t('users.edit') : t('users.add')"
      width="480px"
      destroy-on-close
    >
      <el-form :model="form" label-width="80px">
        <el-form-item :label="t('users.username')"><el-input v-model="form.username" :disabled="!!form.id" /></el-form-item>
        <el-form-item :label="t('users.password')"><el-input v-model="form.password" type="password" show-password :placeholder="form.id ? t('users.passwordPlaceholderEdit') : ''" /></el-form-item>
        <el-form-item v-if="form.id" :label="t('common.status')">
          <el-switch v-model="form.status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
        <el-button type="primary" @click="save">{{ t('common.save') }}</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="logsVisible"
      :title="t('users.accessLogsTitle', { name: logsUser?.username || '' })"
      width="720px"
      destroy-on-close
    >
      <p class="form-hint form-hint--flush u-mb-4">{{ t('users.logsHint', { n: logs.length }) }}</p>
      <el-table :data="logs" v-loading="logsLoading" size="small" class="table-scroll--lg">
        <el-table-column :label="t('common.time')" width="168">
          <template #default="{ row }">{{ formatDateTime(row.created_at) }}</template>
        </el-table-column>
        <el-table-column :label="t('common.type')" width="72">
          <template #default="{ row }">
            <el-tag :type="row.action === 'login' ? 'success' : 'info'" size="small">
              {{ row.action === 'login' ? t('users.login') : t('users.visit') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="resource_label" :label="t('common.resource')" min-width="140" show-overflow-tooltip />
        <el-table-column prop="method" :label="t('common.method')" width="72" />
        <el-table-column prop="path" :label="t('common.path')" min-width="160" show-overflow-tooltip />
        <el-table-column prop="ip" label="IP" width="120" />
        <el-table-column prop="user_agent" label="UA" min-width="140" show-overflow-tooltip />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, 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'
import { formatDateTime } from '@/utils/datetime'

const { t } = useI18n()

const list = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const logsVisible = ref(false)
const logsLoading = ref(false)
const logs = ref([])
const logsUser = ref(null)
const form = reactive({ id: null, username: '', password: '', status: true })

async function load() {
  loading.value = true
  try {
    const { data } = await api.get('/users')
    list.value = data
  } finally {
    loading.value = false
  }
}

function openDialog(row) {
  if (row) Object.assign(form, { id: row.id, username: row.username, password: '', status: row.status })
  else Object.assign(form, { id: null, username: '', password: '', status: true })
  dialogVisible.value = true
}

async function openLogs(row) {
  logsUser.value = row
  logsVisible.value = true
  logsLoading.value = true
  logs.value = []
  try {
    const { data } = await api.get(`/users/${row.id}/access-logs`, { params: { limit: 200 } })
    logs.value = data.items || []
  } catch (e) {
    ElMessage.error(e.response?.data?.error || t('message.loadFailed'))
  } finally {
    logsLoading.value = false
  }
}

async function save() {
  const payload = { username: form.username, password: form.password, role: 'visitor' }
  if (form.id) {
    const body = { password: form.password, role: 'visitor', status: form.status }
    await api.put(`/users/${form.id}`, body)
  } else {
    await api.post('/users', payload)
  }
  ElMessage.success(t('message.saveSuccess'))
  dialogVisible.value = false
  load()
}

async function remove(row) {
  await ElMessageBox.confirm(t('users.confirmDelete'), t('common.hint'), { type: 'warning' })
  await api.delete(`/users/${row.id}`)
  ElMessage.success(t('message.deleteSuccess'))
  load()
}

onMounted(load)
</script>
