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

    <AppCard v-loading="loading" padded>
      <el-alert v-if="note" :title="note" type="info" show-icon :closable="false" class="u-mb-4" />

      <el-form :model="form" label-width="120px" class="settings-form">
        <div class="section-title">{{ t('settings.listenPorts') }}</div>
        <el-form-item :label="t('settings.bridgeAddr')">
          <el-input v-model="form.server.bridge_addr" placeholder=":8528" />
        </el-form-item>
        <el-form-item :label="t('settings.httpAddr')">
          <el-input v-model="form.server.http_addr" placeholder=":8529" />
        </el-form-item>
        <el-form-item :label="t('settings.httpProxyPort')">
          <el-input-number v-model="form.server.http_proxy_port" :min="1" :max="65535" />
        </el-form-item>
        <el-form-item :label="t('settings.httpsProxyPort')">
          <el-input-number v-model="form.server.https_proxy_port" :min="1" :max="65535" />
        </el-form-item>
        <el-form-item :label="t('settings.tlsCert')">
          <el-input v-model="form.server.tls_cert_file" :placeholder="t('settings.tlsOptional')" />
        </el-form-item>
        <el-form-item :label="t('settings.tlsKey')">
          <el-input v-model="form.server.tls_key_file" :placeholder="t('settings.tlsOptional')" />
        </el-form-item>

        <div class="section-title">{{ t('settings.authSecurity') }}</div>
        <el-form-item :label="t('settings.jwtSecret')">
          <el-input v-model="form.auth.jwt_secret" type="password" show-password :placeholder="t('settings.jwtSecretPlaceholder')" />
        </el-form-item>
        <el-form-item :label="t('settings.tokenTtl')">
          <el-input-number v-model="form.auth.token_ttl_hours" :min="1" :max="720" />
        </el-form-item>
        <el-form-item :label="t('settings.loginMaxAttempts')">
          <el-input-number v-model="form.auth.login_max_attempts" :min="1" :max="100" />
        </el-form-item>
        <el-form-item :label="t('settings.loginWindow')">
          <el-input-number v-model="form.auth.login_window_min" :min="1" :max="1440" />
        </el-form-item>
        <el-form-item :label="t('settings.loginLockout')">
          <el-input-number v-model="form.auth.login_lockout_min" :min="1" :max="1440" />
        </el-form-item>

        <div class="section-title">{{ t('settings.adminAccount') }}</div>
        <el-form-item :label="t('settings.currentPassword')">
          <el-input v-model="pwdForm.current" type="password" show-password autocomplete="current-password" />
        </el-form-item>
        <el-form-item :label="t('settings.newPassword')">
          <el-input v-model="pwdForm.newPwd" type="password" show-password autocomplete="new-password" />
        </el-form-item>
        <el-form-item :label="t('settings.confirmPassword')">
          <el-input v-model="pwdForm.confirm" type="password" show-password autocomplete="new-password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain :loading="pwdSaving" @click="changePassword">{{ t('settings.changePassword') }}</el-button>
        </el-form-item>

        <div class="section-title">{{ t('settings.metrics') }}</div>
        <el-form-item :label="t('settings.flushInterval')">
          <el-input-number v-model="metricsFlushSec" :min="5" :max="3600" />
        </el-form-item>
      </el-form>
    </AppCard>

    <AppCard :title="t('settings.apiKey')" padded>
      <p class="form-hint form-hint--flush card-actions">{{ t('settings.apiKeyHint', { header: 'X-API-Key', doc: 'OpenAPI' }) }}</p>
      <el-button type="primary" size="small" @click="createKeyDialog = true">{{ t('settings.createApiKey') }}</el-button>
      <el-table :data="apiKeys" size="small" class="u-mt-3">
        <el-table-column prop="id" :label="t('common.id')" width="60" />
        <el-table-column prop="name" :label="t('common.name')" />
        <el-table-column prop="key_prefix" :label="t('common.prefix')" width="140" />
        <el-table-column :label="t('common.actions')" width="100">
          <template #default="{ row }">
            <el-button link type="danger" @click="removeKey(row)">{{ t('common.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </AppCard>

    <el-dialog v-model="createKeyDialog" :title="t('settings.createApiKeyTitle')" width="480px">
      <el-form label-width="80px">
        <el-form-item :label="t('common.name')"><el-input v-model="newKeyName" :placeholder="t('settings.apiKeyNamePlaceholder')" /></el-form-item>
      </el-form>
      <el-alert v-if="createdKey" :title="t('settings.apiKeySave', { key: createdKey })" type="warning" show-icon :closable="false" />
      <template #footer>
        <el-button @click="createKeyDialog = false">{{ t('common.close') }}</el-button>
        <el-button type="primary" :disabled="!!createdKey" @click="createKey">{{ t('common.create') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

const { t } = useI18n()

const loading = ref(false)
const saving = ref(false)
const note = ref('')
const metricsFlushSec = ref(30)
const apiKeys = ref([])
const createKeyDialog = ref(false)
const newKeyName = ref('')
const createdKey = ref('')
const pwdSaving = ref(false)
const pwdForm = reactive({ current: '', newPwd: '', confirm: '' })
const form = reactive({
  server: {
    bridge_addr: ':8528',
    http_addr: ':8529',
    http_proxy_port: 8081,
    https_proxy_port: 8443,
    tls_cert_file: '',
    tls_key_file: '',
  },
  auth: {
    jwt_secret: '',
    token_ttl_hours: 24,
    login_max_attempts: 5,
    login_window_min: 5,
    login_lockout_min: 15,
  },
})

async function load() {
  loading.value = true
  try {
    const { data } = await api.get('/settings')
    note.value = data.note || ''
    Object.assign(form.server, data.settings.server)
    Object.assign(form.auth, data.settings.auth)
    form.auth.jwt_secret = ''
    const ms = data.settings.metrics?.flush_interval_sec
    metricsFlushSec.value = ms > 0 ? ms : 30
    await loadApiKeys()
  } finally {
    loading.value = false
  }
}

async function save() {
  saving.value = true
  try {
    const payload = {
      server: { ...form.server },
      auth: { ...form.auth },
      metrics: { flush_interval_sec: metricsFlushSec.value },
    }
    const { data } = await api.put('/settings', payload)
    if (data.restart_required) {
      ElMessage.warning(t('message.savedRestart'))
    } else {
      ElMessage.success(t('message.saved'))
    }
    await load()
  } catch (e) {
    ElMessage.error(e.response?.data?.error || t('message.saveFailed'))
  } finally {
    saving.value = false
  }
}

async function changePassword() {
  if (!pwdForm.current || !pwdForm.newPwd) {
    ElMessage.warning(t('settings.fillPassword'))
    return
  }
  if (pwdForm.newPwd !== pwdForm.confirm) {
    ElMessage.warning(t('settings.passwordMismatch'))
    return
  }
  pwdSaving.value = true
  try {
    await api.put('/auth/me/password', {
      current_password: pwdForm.current,
      new_password: pwdForm.newPwd,
    })
    ElMessage.success(t('message.passwordUpdated'))
    pwdForm.current = ''
    pwdForm.newPwd = ''
    pwdForm.confirm = ''
  } catch (e) {
    ElMessage.error(e.response?.data?.error || t('message.passwordChangeFailed'))
  } finally {
    pwdSaving.value = false
  }
}

async function loadApiKeys() {
  try {
    const { data } = await api.get('/api-keys')
    apiKeys.value = data
  } catch {
    apiKeys.value = []
  }
}

async function createKey() {
  if (!newKeyName.value) {
    ElMessage.warning(t('settings.enterApiKeyName'))
    return
  }
  const { data } = await api.post('/api-keys', { name: newKeyName.value })
  createdKey.value = data.api_key
  ElMessage.success(t('message.apiKeyCreated'))
  loadApiKeys()
}

async function removeKey(row) {
  await api.delete(`/api-keys/${row.id}`)
  ElMessage.success(t('message.deleteSuccess'))
  loadApiKeys()
}

onMounted(load)
</script>
