<template>
  <div class="page">
    <PageHeader :title="t('clients.title')" :description="t('clients.description')">
      <template #actions>
        <el-button @click="load">{{ t('common.refresh') }}</el-button>
        <el-button type="primary" @click="openDialog()">{{ t('clients.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="name" :label="t('common.name')" min-width="120" />
        <el-table-column prop="verify_key" :label="t('clients.verifyKey')" min-width="200" show-overflow-tooltip />
        <el-table-column :label="t('common.status')" width="90">
          <template #default="{ row }">
            <el-tag :type="row.online ? 'success' : 'info'" size="small">
              {{ row.online ? t('common.online') : t('common.offline') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="t('common.traffic')" width="120">
          <template #default="{ row }">
            {{ formatBytes((row.inlet_flow || 0) + (row.export_flow || 0)) }}
          </template>
        </el-table-column>
        <el-table-column :label="t('common.actions')" width="140" fixed="right">
          <template #default="{ row }">
            <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('clients.edit') : t('clients.add')"
      width="560px"
      destroy-on-close
    >
      <el-form :model="form" label-width="100px">
        <el-form-item :label="t('common.name')"><el-input v-model="form.name" /></el-form-item>
        <el-form-item :label="t('clients.rateLimit')"><el-input-number v-model="form.rate_limit" :min="0" class="w-full" /></el-form-item>
        <el-form-item :label="t('clients.maxConn')"><el-input-number v-model="form.max_conn" :min="0" class="w-full" /></el-form-item>
        <ProxyHeadersFields
          v-model:ip-forward-mode="form.ip_forward_mode"
          v-model:custom-headers="form.custom_headers"
        />
        <el-form-item :label="t('common.enabled')"><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>
  </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 ProxyHeadersFields from '@/components/ProxyHeadersFields.vue'
import api from '@/api'
import { formatBytes } from '@/utils/format'

const { t } = useI18n()
const list = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const form = reactive({
  id: null,
  name: '',
  rate_limit: 0,
  max_conn: 0,
  ip_forward_mode: 'replace',
  custom_headers: '',
  status: true,
})

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

function openDialog(row) {
  if (row) Object.assign(form, { ...row })
  else Object.assign(form, { id: null, name: '', rate_limit: 0, max_conn: 0, ip_forward_mode: 'replace', custom_headers: '', status: true })
  dialogVisible.value = true
}

async function save() {
  if (form.id) await api.put(`/clients/${form.id}`, form)
  else await api.post('/clients', form)
  ElMessage.success(t('message.saveSuccess'))
  dialogVisible.value = false
  load()
}

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

onMounted(load)
</script>
