<template>
  <div class="w-full animate-reveal">
    <div class="flex items-center justify-between mb-6">
      <h1 class="text-2xl font-serif italic text-white">系统配置管理</h1>
    </div>

    <div v-if="loading" class="admin-card p-16 text-center text-art-muted">加载中...</div>

    <div v-else class="space-y-6">
      <!-- Tab bar -->
      <div class="flex flex-wrap gap-2 border-b border-white/10 pb-1">
        <button
          v-for="tab in tabs"
          :key="tab.id"
          type="button"
          class="px-4 py-2 text-sm rounded-t-lg transition-colors"
          :class="activeTab === tab.id
            ? 'text-art-accent border-b-2 border-art-accent bg-white/5'
            : 'text-art-muted hover:text-white hover:bg-white/5'"
          @click="activeTab = tab.id"
        >
          {{ tab.label }}
        </button>
      </div>

      <!-- Schema group tabs -->
      <div
        v-for="group in SETTING_GROUPS"
        v-show="activeTab === group.id"
        :key="group.id"
        class="admin-card p-6 border border-white/10"
      >
        <h2 class="text-lg font-medium text-white mb-1">{{ group.label }}</h2>
        <p class="text-xs text-art-muted mb-5">管理 {{ group.label }} 相关配置项</p>

        <div class="space-y-5">
          <div
            v-for="schema in getGroupItems(group.id)"
            :key="schema.key"
            class="space-y-2"
          >
            <label class="block text-sm font-medium text-white">{{ schema.label }}</label>
            <p class="text-xs text-art-muted">{{ schema.description }}</p>

            <div v-if="schema.type === 'menu-checkboxes'" class="grid grid-cols-1 md:grid-cols-2 gap-3 mt-2">
              <label
                v-for="menu in MENU_OPTIONS"
                :key="menu.key"
                class="flex items-center gap-3 cursor-pointer p-3 rounded-lg border border-white/10 bg-white/5 hover:bg-white/10 transition-all"
              >
                <input type="checkbox" :value="menu.key" v-model="selectedMenus" class="accent-art-accent" />
                <span class="text-sm text-white/90">{{ menu.label }}</span>
              </label>
            </div>

            <textarea
              v-else-if="schema.type === 'textarea'"
              v-model="formValues[schema.key]"
              rows="3"
              class="admin-input resize-none w-full"
            />

            <input
              v-else-if="schema.type === 'number'"
              v-model="formValues[schema.key]"
              type="number"
              min="1"
              class="admin-input w-full max-w-xs"
            />

            <EmailAutocomplete
              v-else-if="schema.type === 'email'"
              :name="schema.key"
              :label="schema.label"
              v-model="formValues[schema.key]"
              variant="admin"
              :placeholder="schema.default || 'example@domain.com'"
            />

            <input
              v-else
              v-model="formValues[schema.key]"
              type="text"
              class="admin-input w-full"
            />
          </div>
        </div>

        <div v-if="getGroupItems(group.id).length" class="pt-5 mt-5 border-t border-white/5">
          <button
            type="button"
            class="admin-btn-primary"
            :disabled="savingGroup === group.id"
            @click="saveGroup(group.id)"
          >
            {{ savingGroup === group.id ? '保存中...' : `保存${group.label}` }}
          </button>
        </div>
      </div>

      <!-- Custom tab -->
      <div v-show="activeTab === 'custom'" class="admin-card p-6 border border-white/10 border-dashed">
        <h2 class="text-lg font-medium text-white mb-4">自定义配置</h2>
        <div v-if="customSettings.length === 0" class="text-sm text-art-muted">暂无自定义配置项</div>
        <div v-else class="space-y-4">
          <div v-for="setting in customSettings" :key="setting.id" class="flex gap-3 items-start">
            <div class="flex-1 space-y-2">
              <input v-model="setting.value" class="admin-input w-full font-mono text-sm" />
              <p class="text-xs text-art-muted">{{ setting.keyName }} — {{ setting.description || '无描述' }}</p>
            </div>
            <button type="button" class="admin-btn-danger text-xs shrink-0" @click="deleteSetting(setting.keyName)">删除</button>
          </div>
        </div>

        <form @submit.prevent="saveNewSetting" class="mt-6 pt-6 border-t border-white/5 grid grid-cols-1 md:grid-cols-3 gap-3">
          <input v-model="newForm.keyName" class="admin-input" placeholder="键名" required />
          <input v-model="newForm.value" class="admin-input" placeholder="值" required />
          <input v-model="newForm.description" class="admin-input" placeholder="描述" />
          <button type="submit" class="admin-btn-secondary md:col-span-3">新增自定义配置</button>
        </form>
      </div>

      <div class="flex justify-end">
        <button type="button" class="admin-btn-search px-8" :disabled="savingAll" @click="saveAll">
          {{ savingAll ? '保存中...' : '保存全部配置' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import {
  getSettings,
  createSetting,
  batchUpdateSettings,
  deleteSetting as deleteSettingApi,
  type Setting,
} from '../../services/api'
import { useToast } from '../../composables/useToast'
import { usePublicSettings } from '../../composables/usePublicSettings'
import EmailAutocomplete from '../../components/ui/EmailAutocomplete.vue'
import {
  SETTING_GROUPS,
  SETTINGS_SCHEMA,
  MENU_OPTIONS,
  getSchemaKeys,
  type SettingSchemaItem,
} from '../../config/settingsSchema'

const toast = useToast()
const { invalidate: invalidatePublicSettings } = usePublicSettings()

const loading = ref(true)
const savingAll = ref(false)
const savingGroup = ref<string | null>(null)
const activeTab = ref<SettingSchemaItem['group'] | 'custom'>('site')
const settings = ref<Setting[]>([])
const selectedMenus = ref<string[]>([])
const formValues = reactive<Record<string, string>>({})

const newForm = ref({ keyName: '', value: '', description: '' })

const schemaKeys = getSchemaKeys()

const tabs = computed(() => [
  ...SETTING_GROUPS.map(g => ({ id: g.id as SettingSchemaItem['group'] | 'custom', label: g.label })),
  { id: 'custom' as const, label: '自定义' },
])

const customSettings = computed(() =>
  settings.value.filter(s => !schemaKeys.includes(s.keyName))
)

const getGroupItems = (groupId: SettingSchemaItem['group']) =>
  SETTINGS_SCHEMA.filter(s => s.group === groupId)

const initFormValues = () => {
  for (const schema of SETTINGS_SCHEMA) {
    const existing = settings.value.find(s => s.keyName === schema.key)
    formValues[schema.key] = existing?.value ?? schema.default
  }

  const menuVal = formValues.visible_menus || ''
  try {
    const parsed = JSON.parse(menuVal)
    selectedMenus.value = Array.isArray(parsed) ? parsed : MENU_OPTIONS.map(m => m.key)
  } catch {
    selectedMenus.value = menuVal
      ? menuVal.split(',').map(m => m.trim()).filter(Boolean)
      : MENU_OPTIONS.map(m => m.key)
  }
}

const buildPayload = (): Record<string, string> => {
  const payload: Record<string, string> = { ...formValues }
  payload.visible_menus = JSON.stringify(selectedMenus.value)
  return payload
}

const fetchSettings = async () => {
  loading.value = true
  try {
    settings.value = await getSettings()

    for (const schema of SETTINGS_SCHEMA) {
      if (!settings.value.find(s => s.keyName === schema.key)) {
        await createSetting({
          keyName: schema.key,
          value: schema.default,
          description: schema.description,
        })
      }
    }

    if (SETTINGS_SCHEMA.some(s => !settings.value.find(existing => existing.keyName === s.key))) {
      settings.value = await getSettings()
    }

    initFormValues()
  } catch {
    toast.showToast('获取系统配置失败', 'error')
  } finally {
    loading.value = false
  }
}

const persistPayload = async (payload: Record<string, string>) => {
  await batchUpdateSettings(payload)
  invalidatePublicSettings()
  if (typeof window !== 'undefined') {
    window.dispatchEvent(new CustomEvent('public-settings-changed'))
  }
  await fetchSettings()
}

const saveGroup = async (groupId: SettingSchemaItem['group']) => {
  savingGroup.value = groupId
  try {
    const keys = getGroupItems(groupId).map(s => s.key)
    const payload: Record<string, string> = {}
    for (const key of keys) {
      if (key === 'visible_menus') {
        payload[key] = JSON.stringify(selectedMenus.value)
      } else {
        payload[key] = formValues[key] ?? ''
      }
    }
    await persistPayload(payload)
    toast.showToast('配置保存成功', 'success')
  } catch {
    toast.showToast('保存配置失败', 'error')
  } finally {
    savingGroup.value = null
  }
}

const saveAll = async () => {
  savingAll.value = true
  try {
    await persistPayload(buildPayload())
    toast.showToast('全部配置已保存', 'success')
  } catch {
    toast.showToast('保存配置失败', 'error')
  } finally {
    savingAll.value = false
  }
}

const saveNewSetting = async () => {
  try {
    await createSetting(newForm.value)
    newForm.value = { keyName: '', value: '', description: '' }
    toast.showToast('配置创建成功', 'success')
    await fetchSettings()
  } catch {
    toast.showToast('创建配置失败', 'error')
  }
}

const deleteSetting = async (keyName: string) => {
  if (!confirm(`确定要删除配置项 "${keyName}" 吗？`)) return
  try {
    await deleteSettingApi(keyName)
    toast.showToast('配置删除成功', 'success')
    await fetchSettings()
  } catch {
    toast.showToast('删除配置失败', 'error')
  }
}

onMounted(fetchSettings)
</script>
