<template>
  <div class="settings-page">
    <div class="page-header">
      <h1 class="page-title">{{ t('Settings') }}</h1>
      <p class="page-description">{{ t('System and personal settings') }}</p>
    </div>

    <n-grid :cols="2" :x-gap="24" :y-gap="24" :responsive="'screen'" :item-responsive="true">
      <!-- 个人设置 -->
      <n-grid-item>
        <n-card :title="t('Personal Settings')">
          <n-form :model="userSettings" label-placement="left" label-width="100px">
            <n-form-item :label="t('Username')">
              <n-input v-model:value="userSettings.username" disabled />
            </n-form-item>
            <n-form-item :label="t('Email')">
              <n-input v-model:value="userSettings.email" :placeholder="t('Enter email')" />
            </n-form-item>
            <n-form-item :label="t('Avatar')">
              <n-upload
                :file-list="fileList"
                :max="1"
                list-type="image-card"
                @change="handleUploadChange"
              >
                {{ t('Click to upload') }}
              </n-upload>
            </n-form-item>
            <n-form-item>
              <n-button type="primary" @click="saveUserSettings">
                {{ t('Save settings') }}
              </n-button>
            </n-form-item>
          </n-form>
        </n-card>
      </n-grid-item>

      <!-- 系统设置 -->
      <n-grid-item>
        <n-card :title="t('System Settings')">
          <n-form :model="systemSettings" label-placement="left" label-width="120px">
            <n-form-item :label="t('App Name')">
              <n-input v-model:value="systemSettings.appName" :placeholder="t('Enter app name')" />
            </n-form-item>
            <n-form-item label="Jingrow API URL">
              <n-input v-model:value="systemSettings.jingrowApiUrl" />
            </n-form-item>
            <n-form-item :label="t('API Key')">
              <n-input v-model:value="systemSettings.apiKey" type="password" show-password-on="click" />
            </n-form-item>
            <n-form-item :label="t('API Secret')">
              <n-input v-model:value="systemSettings.apiSecret" type="password" show-password-on="click" />
            </n-form-item>
            <n-form-item :label="t('Timeout')">
              <n-input-number v-model:value="systemSettings.timeout" :min="5" :max="300" />
            </n-form-item>
            <n-form-item :label="t('Interface Language')">
              <n-select
                v-model:value="systemSettings.language"
                :options="languageOptions"
                style="width: 200px"
                @update:value="changeLanguage"
              />
            </n-form-item>
            <n-form-item :label="t('Items Per Page')">
              <n-select
                v-model:value="systemSettings.itemsPerPage"
                :options="pageSizeOptions"
                style="width: 120px"
              />
            </n-form-item>
            <n-form-item :label="t('Timezone')">
              <n-select
                v-model:value="systemSettings.timezone"
                :options="timezoneOptions"
                style="width: 250px"
                filterable
                :placeholder="t('Select timezone')"
              />
            </n-form-item>
            <n-form-item>
              <n-button type="primary" @click="saveSystemSettings">
                {{ t('Save settings') }}
              </n-button>
            </n-form-item>
          </n-form>
        </n-card>
      </n-grid-item>
    </n-grid>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { NGrid, NGridItem, NCard, NForm, NFormItem, NInput, NButton, NUpload, NInputNumber, NSelect, useMessage } from 'naive-ui'
import { useAuthStore } from '../shared/stores/auth'
import { getCurrentLocale, setLocale, locales, initLocale, t } from '../shared/i18n'

const message = useMessage()
const authStore = useAuthStore()

const userSettings = reactive({
  username: '',
  email: '',
  avatar: ''
})

const systemSettings = reactive({
  appName: localStorage.getItem('appName') || 'Jingrow',
  jingrowApiUrl: (import.meta as any).env.VITE_JINGROW_SERVER_URL || '',
  apiKey: (import.meta as any).env.VITE_JINGROW_API_KEY || '',
  apiSecret: (import.meta as any).env.VITE_JINGROW_API_SECRET || '',
  timeout: 30,
  language: getCurrentLocale(),
  itemsPerPage: parseInt(localStorage.getItem('itemsPerPage') || '10'),
  timezone: localStorage.getItem('timezone') || 'Asia/Shanghai'
})

const fileList = ref([])

// 语言选项
const languageOptions = locales.map(locale => ({
  label: `${locale.flag} ${locale.name}`,
  value: locale.code
}))

// 每页数量选项
const pageSizeOptions = [
  { label: '10', value: 10 },
  { label: '20', value: 20 },
  { label: '50', value: 50 },
  { label: '100', value: 100 }
]

// 时区选项
const timezoneOptions = [
  { label: 'Asia/Shanghai (中国标准时间)', value: 'Asia/Shanghai' },
  { label: 'Asia/Tokyo (日本标准时间)', value: 'Asia/Tokyo' },
  { label: 'Asia/Seoul (韩国标准时间)', value: 'Asia/Seoul' },
  { label: 'Asia/Hong_Kong (香港时间)', value: 'Asia/Hong_Kong' },
  { label: 'Asia/Taipei (台北时间)', value: 'Asia/Taipei' },
  { label: 'Asia/Singapore (新加坡时间)', value: 'Asia/Singapore' },
  { label: 'UTC (协调世界时)', value: 'UTC' },
  { label: 'America/New_York (美国东部时间)', value: 'America/New_York' },
  { label: 'America/Los_Angeles (美国西部时间)', value: 'America/Los_Angeles' },
  { label: 'Europe/London (英国时间)', value: 'Europe/London' },
  { label: 'Europe/Paris (法国时间)', value: 'Europe/Paris' },
  { label: 'Europe/Berlin (德国时间)', value: 'Europe/Berlin' },
  { label: 'Australia/Sydney (澳大利亚东部时间)', value: 'Australia/Sydney' },
  { label: 'Pacific/Auckland (新西兰时间)', value: 'Pacific/Auckland' }
]

const handleUploadChange = (options: any) => {
  fileList.value = options.fileList
}

const changeLanguage = (locale: string) => {
  setLocale(locale)
  message.success(t('Language updated'))
}

const saveUserSettings = () => {
  message.success(t('User settings saved'))
}

const saveSystemSettings = () => {
  // 保存应用名称
  localStorage.setItem('appName', systemSettings.appName)
  // 保存每页数量设置
  localStorage.setItem('itemsPerPage', systemSettings.itemsPerPage.toString())
  // 保存时区设置
  localStorage.setItem('timezone', systemSettings.timezone)
  message.success(t('System settings saved'))
  
  // 保存成功后自动刷新页面，让新设置生效
  setTimeout(() => {
    window.location.reload()
  }, 1000)
}

onMounted(() => {
  initLocale()
  systemSettings.language = getCurrentLocale()
  if (authStore.user) {
    userSettings.username = authStore.user.username
    userSettings.email = authStore.user.email
    userSettings.avatar = authStore.user.avatar || ''
  }
})
</script>

<style scoped>
.settings-page {
  width: 100%;
  padding: 0 16px;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-description {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .settings-page {
    padding: 0 12px;
  }
  
  .page-header {
    margin-bottom: 16px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .page-description {
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .settings-page {
    padding: 0 8px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .page-description {
    font-size: 13px;
  }
}
</style>
