<script setup lang="ts">
import { onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { fetchSettings, saveSettings } from '@/api/admin'

const form = reactive<Record<string, unknown>>({
  'site.name': 'QuickQuiz',
  'register.enabled': true,
  'invite.required': true,
  'test.default_duration_minutes': 45,
  'mail.enabled': false,
  'sms.enabled': false,
})

async function load() {
  const response = await fetchSettings()
  response.data.forEach((item) => {
    form[item.key] = item.value
  })
}

async function submit() {
  await saveSettings(form)
  ElMessage.success('配置已保存')
}

onMounted(load)
</script>

<template>
  <section class="panel p-5">
    <h1 class="page-title mb-4">系统配置</h1>
    <ElForm label-position="top" class="settings-form">
      <ElFormItem label="站点名称"><ElInput v-model="form['site.name']" /></ElFormItem>
      <ElFormItem label="默认测试时长"><ElInputNumber v-model="form['test.default_duration_minutes']" :min="1" /></ElFormItem>
      <ElFormItem label="注册开关"><ElSwitch v-model="form['register.enabled']" /></ElFormItem>
      <ElFormItem label="邀请码注册"><ElSwitch v-model="form['invite.required']" /></ElFormItem>
      <ElFormItem label="邮件服务"><ElSwitch v-model="form['mail.enabled']" /></ElFormItem>
      <ElFormItem label="短信服务"><ElSwitch v-model="form['sms.enabled']" /></ElFormItem>
      <ElButton type="primary" @click="submit">保存配置</ElButton>
    </ElForm>
  </section>
</template>

<style scoped>
.settings-form {
  max-width: 560px;
}
</style>
