<template>
  <div class="page">
    <PageHeader
      :title="t('settings.title')"
      :description="t('settings.description')"
    />

    <div class="page-form">
      <AppCard :title="t('settings.securitySession')" padded>
        <el-form v-loading="loading" class="settings-form" label-width="120px">
          <el-form-item :label="t('settings.encryptionKey')">
            <el-input
              v-model="form.encryption_key"
              type="password"
              show-password
              :placeholder="t('settings.encryptionKeyPlaceholder')"
            />
            <div class="form-hint">{{ t('settings.encryptionKeyCurrent', { hint: settings.encryption_key_hint }) }}</div>
          </el-form-item>
          <el-form-item :label="t('settings.sessionTtl')">
            <el-input-number v-model="form.session_ttl_seconds" :min="300" :max="604800" />
          </el-form-item>
          <el-form-item :label="t('settings.loginMaxAttempts')">
            <el-input-number v-model="form.login_max_attempts" :min="1" :max="100" />
          </el-form-item>
          <el-form-item :label="t('settings.loginLockout')">
            <el-input-number v-model="form.login_lockout_seconds" :min="60" :max="86400" />
          </el-form-item>
          <el-form-item :label="t('settings.trustedProxies')">
            <el-input
              v-model="trustedProxiesText"
              type="textarea"
              :rows="3"
              :placeholder="t('settings.trustedProxiesPlaceholder')"
            />
          </el-form-item>
        </el-form>
      </AppCard>

      <AppCard :title="t('settings.imageStorage')" padded>
        <el-form class="settings-form" label-width="160px">
          <el-form-item :label="t('settings.imageStoragePath')">
            <el-input v-model="form.image_storage_path" placeholder="images" />
          </el-form-item>
          <el-form-item :label="t('settings.publicBaseUrl')">
            <el-input v-model="form.public_base_url" placeholder="https://gateway.example.com" />
          </el-form-item>
          <el-form-item :label="t('settings.signedUrlTtl')">
            <el-input-number v-model="form.signed_url_ttl_seconds" :min="60" :max="604800" />
          </el-form-item>
          <el-form-item :label="t('settings.predictionWait')">
            <el-input-number v-model="form.prediction_wait_seconds" :min="5" :max="300" />
          </el-form-item>
        </el-form>
      </AppCard>

      <AppCard :title="t('settings.gatewayMonitor')" padded>
        <el-form class="settings-form" label-width="120px">
          <el-form-item :label="t('settings.usageFlush')">
            <el-input-number v-model="form.usage_flush_seconds" :min="1" :max="300" />
          </el-form-item>
          <el-form-item :label="t('settings.healthCheck')">
            <el-input-number v-model="form.health_check_seconds" :min="5" :max="3600" />
          </el-form-item>
          <el-form-item :label="t('settings.gatewayMaxRetries')">
            <el-input-number v-model="form.gateway_max_retries" :min="1" :max="10" />
          </el-form-item>
          <el-form-item :label="t('settings.retryBackoff')">
            <el-input-number v-model="form.gateway_retry_backoff_ms" :min="0" :max="10000" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="saving" @click="saveSettings">{{ t('settings.saveSettings') }}</el-button>
          </el-form-item>
        </el-form>
      </AppCard>
    </div>

    <AppCard :title="t('settings.changePassword')" padded class="page-form page-form--narrow">
      <el-form label-width="100px">
        <el-form-item :label="t('settings.oldPassword')">
          <el-input v-model="oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item :label="t('settings.newPassword')">
          <el-input v-model="newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitPassword">{{ t('settings.savePassword') }}</el-button>
        </el-form-item>
      </el-form>
    </AppCard>
  </div>
</template>

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

const { t } = useI18n()

interface SystemSettings {
  encryption_key_set: boolean
  encryption_key_hint: string
  session_ttl_seconds: number
  login_max_attempts: number
  login_lockout_seconds: number
  trusted_proxies: string[]
  usage_flush_seconds: number
  health_check_seconds: number
  gateway_max_retries: number
  gateway_retry_backoff_ms: number
  image_storage_path?: string
  public_base_url?: string
  signed_url_ttl_seconds?: number
  prediction_wait_seconds?: number
}

const loading = ref(false)
const saving = ref(false)
const oldPassword = ref('')
const newPassword = ref('')
const trustedProxiesText = ref('')

const settings = reactive<SystemSettings>({
  encryption_key_set: false,
  encryption_key_hint: '',
  session_ttl_seconds: 86400,
  login_max_attempts: 5,
  login_lockout_seconds: 900,
  trusted_proxies: [],
  usage_flush_seconds: 5,
  health_check_seconds: 30,
  gateway_max_retries: 3,
  gateway_retry_backoff_ms: 200,
})

const form = reactive({
  encryption_key: '',
  session_ttl_seconds: 86400,
  login_max_attempts: 5,
  login_lockout_seconds: 900,
  usage_flush_seconds: 5,
  health_check_seconds: 30,
  gateway_max_retries: 3,
  gateway_retry_backoff_ms: 200,
  image_storage_path: 'images',
  public_base_url: '',
  signed_url_ttl_seconds: 3600,
  prediction_wait_seconds: 60,
})

function applySettings(data: SystemSettings) {
  Object.assign(settings, data)
  form.session_ttl_seconds = data.session_ttl_seconds
  form.login_max_attempts = data.login_max_attempts
  form.login_lockout_seconds = data.login_lockout_seconds
  form.usage_flush_seconds = data.usage_flush_seconds
  form.health_check_seconds = data.health_check_seconds
  form.gateway_max_retries = data.gateway_max_retries
  form.gateway_retry_backoff_ms = data.gateway_retry_backoff_ms
  form.image_storage_path = data.image_storage_path || 'images'
  form.public_base_url = data.public_base_url || ''
  form.signed_url_ttl_seconds = data.signed_url_ttl_seconds ?? 3600
  form.prediction_wait_seconds = data.prediction_wait_seconds ?? 60
  trustedProxiesText.value = (data.trusted_proxies || []).join('\n')
  form.encryption_key = ''
}

async function loadSettings() {
  loading.value = true
  try {
    const { data } = await api.get<SystemSettings>('/settings')
    applySettings(data)
  } finally {
    loading.value = false
  }
}

async function saveSettings() {
  saving.value = true
  try {
    const payload: Record<string, unknown> = {
      session_ttl_seconds: form.session_ttl_seconds,
      login_max_attempts: form.login_max_attempts,
      login_lockout_seconds: form.login_lockout_seconds,
      trusted_proxies: trustedProxiesText.value
        .split('\n')
        .map((s) => s.trim())
        .filter(Boolean),
      usage_flush_seconds: form.usage_flush_seconds,
      health_check_seconds: form.health_check_seconds,
      gateway_max_retries: form.gateway_max_retries,
      gateway_retry_backoff_ms: form.gateway_retry_backoff_ms,
      image_storage_path: form.image_storage_path,
      public_base_url: form.public_base_url,
      signed_url_ttl_seconds: form.signed_url_ttl_seconds,
      prediction_wait_seconds: form.prediction_wait_seconds,
    }
    if (form.encryption_key.trim()) {
      payload.encryption_key = form.encryption_key.trim()
    }
    const { data } = await api.put<SystemSettings>('/settings', payload)
    applySettings(data)
    ElMessage.success(t('settings.settingsSaved'))
  } finally {
    saving.value = false
  }
}

async function submitPassword() {
  await api.put('/password', { old_password: oldPassword.value, new_password: newPassword.value })
  ElMessage.success(t('settings.passwordUpdated'))
  oldPassword.value = ''
  newPassword.value = ''
}

onMounted(loadSettings)
</script>
