<script setup lang="ts">
import { Bell, Database, Loader2, Settings, Shield, ToggleLeft, Trash2, Upload } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { toast } from 'vue-sonner'

import { BasicPage } from '@/components/global-layout'
import api from '@/services/api'

const { t } = useI18n()

const loading = ref(true)
const saving = ref(false)
const uploadingLogo = ref(false)
const uploadingFavicon = ref(false)
const activeTab = ref('basic')

const logoInputRef = ref<HTMLInputElement | null>(null)
const faviconInputRef = ref<HTMLInputElement | null>(null)

const basicForm = ref({
  site_name: '',
  site_logo: '',
  site_favicon: '',
  site_footer: '',
})

const securityForm = ref({
  enable_captcha: true,
  login_fail_lock_count: 5,
  login_fail_lock_minutes: 30,
  password_min_length: 6,
  session_timeout: 24,
})

const backupForm = ref({
  enable_backup: false,
  backup_interval: 24,
  backup_retention: 7,
  backup_storage_type: 'local',
})

const featureForm = ref({
  enable_ticket_system: true,
  default_theme: 'system',
  enable_multi_lang: false,
})

const notificationForm = ref({
  enable_notification: false,
  admin_notify_email: '',
  notify_on_login: false,
  notify_on_recharge: true,
  notify_on_ticket: true,
})

const cleanupForm = ref({
  enable_auto_cleanup: false,
  cleanup_interval_hours: 24,
  captcha_retention_days: 1,
  verify_code_retention_days: 7,
  api_usage_retention_days: 30,
  webhook_log_retention_days: 30,
  device_session_retention_days: 7,
})

const cleanupLoading = ref(false)
const manualCleanupLoading = ref(false)

async function loadSettings() {
  loading.value = true
  try {
    const data = await api.get<any>('/dev/system-settings')
    if (data) {
      basicForm.value = {
        site_name: data.site_name || '',
        site_logo: data.site_logo || '',
        site_favicon: data.site_favicon || '',
        site_footer: data.site_footer || '',
      }
      securityForm.value = {
        enable_captcha: data.enable_captcha ?? true,
        login_fail_lock_count: data.login_fail_lock_count || 5,
        login_fail_lock_minutes: data.login_fail_lock_minutes || 30,
        password_min_length: data.password_min_length || 6,
        session_timeout: data.session_timeout || 24,
      }
      backupForm.value = {
        enable_backup: data.enable_backup ?? false,
        backup_interval: data.backup_interval || 24,
        backup_retention: data.backup_retention || 7,
        backup_storage_type: data.backup_storage_type || 'local',
      }
      featureForm.value = {
        enable_ticket_system: data.enable_ticket_system ?? true,
        default_theme: data.default_theme || 'system',
        enable_multi_lang: data.enable_multi_lang ?? false,
      }
      notificationForm.value = {
        enable_notification: data.enable_notification ?? false,
        admin_notify_email: data.admin_notify_email || '',
        notify_on_login: data.notify_on_login ?? false,
        notify_on_recharge: data.notify_on_recharge ?? true,
        notify_on_ticket: data.notify_on_ticket ?? true,
      }
      const settings = {
        site_name: data.site_name || '',
        site_logo: data.site_logo || '',
        site_favicon: data.site_favicon || '',
      }
      localStorage.setItem('systemSettings', JSON.stringify(settings))
      window.dispatchEvent(new CustomEvent('system-settings-changed', { detail: settings }))
    }
  }
  catch (error) {
    toast.error(t('admin.systemSettings.loadFailed'))
  }
  finally {
    loading.value = false
  }

  try {
    const cleanupData = await api.get<any>('/dev/system-settings/cleanup')
    if (cleanupData) {
      cleanupForm.value = {
        enable_auto_cleanup: cleanupData.enable_auto_cleanup ?? false,
        cleanup_interval_hours: cleanupData.cleanup_interval_hours || 24,
        captcha_retention_days: cleanupData.captcha_retention_days || 1,
        verify_code_retention_days: cleanupData.verify_code_retention_days || 7,
        api_usage_retention_days: cleanupData.api_usage_retention_days || 30,
        webhook_log_retention_days: cleanupData.webhook_log_retention_days || 30,
        device_session_retention_days: cleanupData.device_session_retention_days || 7,
      }
    }
  }
  catch (error) {
    // ignore
  }
}

async function saveSettings() {
  saving.value = true
  try {
    const payload = {
      ...basicForm.value,
      ...securityForm.value,
      ...backupForm.value,
      ...featureForm.value,
      ...notificationForm.value,
    }
    await api.put('/dev/system-settings', payload)
    toast.success(t('admin.systemSettings.saveSuccess'))
    updateGlobalSettings()
  }
  catch (error) {
    toast.error(t('admin.systemSettings.saveFailed'))
  }
  finally {
    saving.value = false
  }
}

function updateGlobalSettings() {
  const settings = {
    site_name: basicForm.value.site_name,
    site_logo: basicForm.value.site_logo,
    site_favicon: basicForm.value.site_favicon,
  }
  localStorage.setItem('systemSettings', JSON.stringify(settings))
  window.dispatchEvent(new CustomEvent('system-settings-changed', { detail: settings }))
}

async function saveCleanupSettings() {
  cleanupLoading.value = true
  try {
    await api.put('/dev/system-settings/cleanup', cleanupForm.value)
    toast.success(t('admin.systemSettings.cleanup.cleanupSaveSuccess'))
  }
  catch (error) {
    toast.error(t('admin.systemSettings.cleanup.cleanupSaveFailed'))
  }
  finally {
    cleanupLoading.value = false
  }
}

async function runManualCleanup() {
  manualCleanupLoading.value = true
  try {
    await api.post('/dev/system-settings/cleanup/run')
    toast.success(t('admin.systemSettings.cleanup.manualCleanupSuccess'))
  }
  catch (error) {
    toast.error(t('admin.systemSettings.cleanup.manualCleanupFailed'))
  }
  finally {
    manualCleanupLoading.value = false
  }
}

function triggerLogoUpload() {
  logoInputRef.value?.click()
}

async function handleLogoUpload(event: Event) {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file)
    return

  uploadingLogo.value = true
  try {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('type', 'logo')

    const data = await api.postFormData<any>('/dev/system-settings/upload', formData)
    basicForm.value.site_logo = data.url
    toast.success(t('admin.systemSettings.upload.logoSuccess'))
  }
  catch (error: any) {
    toast.error(error.message || t('admin.systemSettings.upload.uploadFailed'))
  }
  finally {
    uploadingLogo.value = false
    target.value = ''
  }
}

function triggerFaviconUpload() {
  faviconInputRef.value?.click()
}

async function handleFaviconUpload(event: Event) {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file)
    return

  uploadingFavicon.value = true
  try {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('type', 'favicon')

    const data = await api.postFormData<any>('/dev/system-settings/upload', formData)
    basicForm.value.site_favicon = data.url
    toast.success(t('admin.systemSettings.upload.faviconSuccess'))
  }
  catch (error: any) {
    toast.error(error.message || t('admin.systemSettings.upload.uploadFailed'))
  }
  finally {
    uploadingFavicon.value = false
    target.value = ''
  }
}

const tabs = computed(() => [
  { id: 'basic', label: t('admin.systemSettings.tabs.basic'), icon: Settings },
  { id: 'security', label: t('admin.systemSettings.tabs.security'), icon: Shield },
  { id: 'backup', label: t('admin.systemSettings.tabs.backup'), icon: Database },
  { id: 'cleanup', label: t('admin.systemSettings.tabs.cleanup'), icon: Trash2 },
  { id: 'feature', label: t('admin.systemSettings.tabs.feature'), icon: ToggleLeft },
  { id: 'notification', label: t('admin.systemSettings.tabs.notification'), icon: Bell },
])

onMounted(() => {
  loadSettings()
})
</script>

<template>
  <BasicPage :title="t('admin.systemSettings.title')" :description="t('admin.systemSettings.description')">
    <div v-if="loading" class="flex items-center justify-center py-8">
      <div class="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
    </div>

    <div v-else class="space-y-6">
      <div class="flex border-b">
        <button
          v-for="tab in tabs"
          :key="tab.id"
          class="flex items-center gap-2 px-4 py-2 text-sm font-medium transition-colors"
          :class="activeTab === tab.id
            ? 'border-b-2 border-primary text-primary'
            : 'text-muted-foreground hover:text-foreground'"
          @click="activeTab = tab.id"
        >
          <component :is="tab.icon" class="h-4 w-4" />
          {{ tab.label }}
        </button>
      </div>

      <UiCard v-show="activeTab === 'basic'">
        <UiCardHeader>
          <UiCardTitle>{{ t('admin.systemSettings.basic.title') }}</UiCardTitle>
          <UiCardDescription>{{ t('admin.systemSettings.basic.description') }}</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-6">
          <div class="space-y-2">
            <UiLabel for="site_name">{{ t('admin.systemSettings.basic.siteName') }}</UiLabel>
            <UiInput id="site_name" v-model="basicForm.site_name" :placeholder="t('admin.systemSettings.basic.siteNamePlaceholder')" />
          </div>

          <div class="space-y-2">
            <UiLabel>{{ t('admin.systemSettings.basic.siteLogo') }}</UiLabel>
            <div class="flex items-start gap-4">
              <div class="flex-1">
                <div class="flex items-center gap-2">
                  <UiButton variant="outline" size="sm" :disabled="uploadingLogo" @click="triggerLogoUpload">
                    <Loader2 v-if="uploadingLogo" class="mr-2 h-4 w-4 animate-spin" />
                    <Upload v-else class="mr-2 h-4 w-4" />
                    {{ t('admin.systemSettings.basic.uploadLogo') }}
                  </UiButton>
                  <span class="text-xs text-muted-foreground">{{ t('admin.systemSettings.basic.logoHint') }}</span>
                </div>
                <input
                  ref="logoInputRef"
                  type="file"
                  accept="image/*"
                  class="hidden"
                  :disabled="uploadingLogo"
                  @change="handleLogoUpload"
                >
                <div v-if="basicForm.site_logo" class="mt-3 flex items-center gap-3">
                  <img
                    :src="basicForm.site_logo"
                    alt="Logo预览"
                    class="h-12 w-auto rounded border object-contain p-1"
                  >
                  <UiButton
                    variant="ghost"
                    size="sm"
                    class="text-destructive hover:text-destructive"
                    @click="basicForm.site_logo = ''"
                  >
                    {{ t('admin.systemSettings.basic.remove') }}
                  </UiButton>
                </div>
              </div>
            </div>
          </div>

          <div class="space-y-2">
            <UiLabel>{{ t('admin.systemSettings.basic.favicon') }}</UiLabel>
            <div class="flex items-start gap-4">
              <div class="flex-1">
                <div class="flex items-center gap-2">
                  <UiButton variant="outline" size="sm" :disabled="uploadingFavicon" @click="triggerFaviconUpload">
                    <Loader2 v-if="uploadingFavicon" class="mr-2 h-4 w-4 animate-spin" />
                    <Upload v-else class="mr-2 h-4 w-4" />
                    {{ t('admin.systemSettings.basic.uploadFavicon') }}
                  </UiButton>
                  <span class="text-xs text-muted-foreground">{{ t('admin.systemSettings.basic.faviconHint') }}</span>
                </div>
                <input
                  ref="faviconInputRef"
                  type="file"
                  accept="image/*"
                  class="hidden"
                  :disabled="uploadingFavicon"
                  @change="handleFaviconUpload"
                >
                <div v-if="basicForm.site_favicon" class="mt-3 flex items-center gap-3">
                  <img
                    :src="basicForm.site_favicon"
                    alt="Favicon预览"
                    class="h-8 w-8 rounded border object-contain p-1"
                  >
                  <UiButton
                    variant="ghost"
                    size="sm"
                    class="text-destructive hover:text-destructive"
                    @click="basicForm.site_favicon = ''"
                  >
                    {{ t('admin.systemSettings.basic.remove') }}
                  </UiButton>
                </div>
              </div>
            </div>
          </div>

          <div class="space-y-2">
            <UiLabel for="site_footer">{{ t('admin.systemSettings.basic.siteFooter') }}</UiLabel>
            <UiInput id="site_footer" v-model="basicForm.site_footer" :placeholder="t('admin.systemSettings.basic.siteFooterPlaceholder')" />
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard v-show="activeTab === 'security'">
        <UiCardHeader>
          <UiCardTitle>{{ t('admin.systemSettings.security.title') }}</UiCardTitle>
          <UiCardDescription>{{ t('admin.systemSettings.security.description') }}</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-6">
          <div class="flex items-center justify-between">
            <div class="space-y-0.5">
              <UiLabel>{{ t('admin.systemSettings.security.enableCaptcha') }}</UiLabel>
              <p class="text-sm text-muted-foreground">
                {{ t('admin.systemSettings.security.enableCaptchaDesc') }}
              </p>
            </div>
            <UiSwitch v-model="securityForm.enable_captcha" />
          </div>

          <div class="grid gap-4 md:grid-cols-2">
            <div class="space-y-2">
              <UiLabel for="login_fail_lock_count">{{ t('admin.systemSettings.security.loginFailLockCount') }}</UiLabel>
              <UiInput
                id="login_fail_lock_count"
                v-model.number="securityForm.login_fail_lock_count"
                type="number"
                min="1"
                max="10"
              />
              <p class="text-xs text-muted-foreground">
                {{ t('admin.systemSettings.security.loginFailLockCountHint') }}
              </p>
            </div>

            <div class="space-y-2">
              <UiLabel for="login_fail_lock_minutes">{{ t('admin.systemSettings.security.lockMinutes') }}</UiLabel>
              <UiInput
                id="login_fail_lock_minutes"
                v-model.number="securityForm.login_fail_lock_minutes"
                type="number"
                min="5"
                max="1440"
              />
              <p class="text-xs text-muted-foreground">
                {{ t('admin.systemSettings.security.lockMinutesHint') }}
              </p>
            </div>
          </div>

          <div class="grid gap-4 md:grid-cols-2">
            <div class="space-y-2">
              <UiLabel for="password_min_length">{{ t('admin.systemSettings.security.passwordMinLength') }}</UiLabel>
              <UiInput
                id="password_min_length"
                v-model.number="securityForm.password_min_length"
                type="number"
                min="6"
                max="32"
              />
              <p class="text-xs text-muted-foreground">
                {{ t('admin.systemSettings.security.passwordMinLengthHint') }}
              </p>
            </div>

            <div class="space-y-2">
              <UiLabel for="session_timeout">{{ t('admin.systemSettings.security.sessionTimeout') }}</UiLabel>
              <UiInput
                id="session_timeout"
                v-model.number="securityForm.session_timeout"
                type="number"
                min="1"
                max="720"
              />
              <p class="text-xs text-muted-foreground">
                {{ t('admin.systemSettings.security.sessionTimeoutHint') }}
              </p>
            </div>
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard v-show="activeTab === 'backup'">
        <UiCardHeader>
          <UiCardTitle>{{ t('admin.systemSettings.backup.title') }}</UiCardTitle>
          <UiCardDescription>{{ t('admin.systemSettings.backup.description') }}</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-6">
          <div class="flex items-center justify-between">
            <div class="space-y-0.5">
              <UiLabel>{{ t('admin.systemSettings.backup.enableBackup') }}</UiLabel>
              <p class="text-sm text-muted-foreground">
                {{ t('admin.systemSettings.backup.enableBackupDesc') }}
              </p>
            </div>
            <UiSwitch v-model="backupForm.enable_backup" />
          </div>

          <div class="grid gap-4 md:grid-cols-2">
            <div class="space-y-2">
              <UiLabel for="backup_interval">{{ t('admin.systemSettings.backup.backupInterval') }}</UiLabel>
              <UiInput
                id="backup_interval"
                v-model.number="backupForm.backup_interval"
                type="number"
                min="1"
                max="168"
              />
              <p class="text-xs text-muted-foreground">
                {{ t('admin.systemSettings.backup.backupIntervalHint') }}
              </p>
            </div>

            <div class="space-y-2">
              <UiLabel for="backup_retention">{{ t('admin.systemSettings.backup.backupRetention') }}</UiLabel>
              <UiInput
                id="backup_retention"
                v-model.number="backupForm.backup_retention"
                type="number"
                min="1"
                max="90"
              />
              <p class="text-xs text-muted-foreground">
                {{ t('admin.systemSettings.backup.backupRetentionHint') }}
              </p>
            </div>
          </div>

          <div class="space-y-2">
            <UiLabel for="backup_storage_type">{{ t('admin.systemSettings.backup.storageType') }}</UiLabel>
            <UiSelect v-model="backupForm.backup_storage_type">
              <UiSelectTrigger>
                <UiSelectValue :placeholder="t('admin.systemSettings.backup.storageTypePlaceholder')" />
              </UiSelectTrigger>
              <UiSelectContent>
                <UiSelectItem value="local">
                  {{ t('admin.systemSettings.backup.local') }}
                </UiSelectItem>
                <UiSelectItem value="s3">
                  {{ t('admin.systemSettings.backup.s3') }}
                </UiSelectItem>
                <UiSelectItem value="webdav">
                  {{ t('admin.systemSettings.backup.webdav') }}
                </UiSelectItem>
                <UiSelectItem value="ftp">
                  {{ t('admin.systemSettings.backup.ftp') }}
                </UiSelectItem>
                <UiSelectItem value="sftp">
                  {{ t('admin.systemSettings.backup.sftp') }}
                </UiSelectItem>
              </UiSelectContent>
            </UiSelect>
            <p class="text-xs text-muted-foreground">
              {{ t('admin.systemSettings.backup.storageTypeHint') }}
            </p>
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard v-show="activeTab === 'feature'">
        <UiCardHeader>
          <UiCardTitle>{{ t('admin.systemSettings.feature.title') }}</UiCardTitle>
          <UiCardDescription>{{ t('admin.systemSettings.feature.description') }}</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-6">
          <div class="flex items-center justify-between">
            <div class="space-y-0.5">
              <UiLabel>{{ t('admin.systemSettings.feature.ticketSystem') }}</UiLabel>
              <p class="text-sm text-muted-foreground">
                {{ t('admin.systemSettings.feature.ticketSystemDesc') }}
              </p>
            </div>
            <UiSwitch v-model="featureForm.enable_ticket_system" />
          </div>

          <div class="flex items-center justify-between">
            <div class="space-y-0.5">
              <UiLabel>{{ t('admin.systemSettings.feature.multiLang') }}</UiLabel>
              <p class="text-sm text-muted-foreground">
                {{ t('admin.systemSettings.feature.multiLangDesc') }}
              </p>
            </div>
            <UiSwitch v-model="featureForm.enable_multi_lang" />
          </div>

          <div class="space-y-2">
            <UiLabel for="default_theme">{{ t('admin.systemSettings.feature.defaultTheme') }}</UiLabel>
            <UiSelect v-model="featureForm.default_theme">
              <UiSelectTrigger>
                <UiSelectValue :placeholder="t('admin.systemSettings.feature.defaultThemePlaceholder')" />
              </UiSelectTrigger>
              <UiSelectContent>
                <UiSelectItem value="system">
                  {{ t('admin.systemSettings.feature.followSystem') }}
                </UiSelectItem>
                <UiSelectItem value="light">
                  {{ t('admin.systemSettings.feature.lightMode') }}
                </UiSelectItem>
                <UiSelectItem value="dark">
                  {{ t('admin.systemSettings.feature.darkMode') }}
                </UiSelectItem>
              </UiSelectContent>
            </UiSelect>
            <p class="text-xs text-muted-foreground">
              {{ t('admin.systemSettings.feature.defaultThemeHint') }}
            </p>
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard v-show="activeTab === 'notification'">
        <UiCardHeader>
          <UiCardTitle>{{ t('admin.systemSettings.notification.title') }}</UiCardTitle>
          <UiCardDescription>{{ t('admin.systemSettings.notification.description') }}</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-6">
          <div class="flex items-center justify-between">
            <div class="space-y-0.5">
              <UiLabel>{{ t('admin.systemSettings.notification.enableNotification') }}</UiLabel>
              <p class="text-sm text-muted-foreground">
                {{ t('admin.systemSettings.notification.enableNotificationDesc') }}
              </p>
            </div>
            <UiSwitch v-model="notificationForm.enable_notification" />
          </div>

          <div class="space-y-2">
            <UiLabel for="admin_notify_email">{{ t('admin.systemSettings.notification.adminNotifyEmail') }}</UiLabel>
            <UiInput
              id="admin_notify_email"
              v-model="notificationForm.admin_notify_email"
              type="email"
              placeholder="admin@example.com"
            />
            <p class="text-xs text-muted-foreground">
              {{ t('admin.systemSettings.notification.adminNotifyEmailHint') }}
            </p>
          </div>

          <div class="space-y-4">
            <UiLabel>{{ t('admin.systemSettings.notification.notifyEvents') }}</UiLabel>
            <div class="space-y-3">
              <div class="flex items-center justify-between">
                <div class="space-y-0.5">
                  <p class="text-sm font-medium">
                    {{ t('admin.systemSettings.notification.loginNotify') }}
                  </p>
                  <p class="text-xs text-muted-foreground">
                    {{ t('admin.systemSettings.notification.loginNotifyDesc') }}
                  </p>
                </div>
                <UiSwitch v-model="notificationForm.notify_on_login" />
              </div>

              <div class="flex items-center justify-between">
                <div class="space-y-0.5">
                  <p class="text-sm font-medium">
                    {{ t('admin.systemSettings.notification.rechargeNotify') }}
                  </p>
                  <p class="text-xs text-muted-foreground">
                    {{ t('admin.systemSettings.notification.rechargeNotifyDesc') }}
                  </p>
                </div>
                <UiSwitch v-model="notificationForm.notify_on_recharge" />
              </div>

              <div class="flex items-center justify-between">
                <div class="space-y-0.5">
                  <p class="text-sm font-medium">
                    {{ t('admin.systemSettings.notification.ticketNotify') }}
                  </p>
                  <p class="text-xs text-muted-foreground">
                    {{ t('admin.systemSettings.notification.ticketNotifyDesc') }}
                  </p>
                </div>
                <UiSwitch v-model="notificationForm.notify_on_ticket" />
              </div>
            </div>
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard v-show="activeTab === 'cleanup'">
        <UiCardHeader>
          <UiCardTitle>{{ t('admin.systemSettings.cleanup.title') }}</UiCardTitle>
          <UiCardDescription>{{ t('admin.systemSettings.cleanup.description') }}</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-6">
          <div class="flex items-center justify-between">
            <div class="space-y-0.5">
              <UiLabel>{{ t('admin.systemSettings.cleanup.enableAutoCleanup') }}</UiLabel>
              <p class="text-sm text-muted-foreground">
                {{ t('admin.systemSettings.cleanup.enableAutoCleanupDesc') }}
              </p>
            </div>
            <UiSwitch v-model="cleanupForm.enable_auto_cleanup" />
          </div>

          <div class="grid gap-4 md:grid-cols-2">
            <div class="space-y-2">
              <UiLabel for="cleanup_interval_hours">{{ t('admin.systemSettings.cleanup.cleanupInterval') }}</UiLabel>
              <UiInput
                id="cleanup_interval_hours"
                v-model.number="cleanupForm.cleanup_interval_hours"
                type="number"
                min="1"
                max="168"
              />
              <p class="text-xs text-muted-foreground">
                {{ t('admin.systemSettings.cleanup.cleanupIntervalHint') }}
              </p>
            </div>

            <div class="space-y-2">
              <UiLabel for="captcha_retention_days">{{ t('admin.systemSettings.cleanup.captchaRetention') }}</UiLabel>
              <UiInput
                id="captcha_retention_days"
                v-model.number="cleanupForm.captcha_retention_days"
                type="number"
                min="1"
                max="30"
              />
              <p class="text-xs text-muted-foreground">
                {{ t('admin.systemSettings.cleanup.captchaRetentionHint') }}
              </p>
            </div>
          </div>

          <div class="grid gap-4 md:grid-cols-2">
            <div class="space-y-2">
              <UiLabel for="verify_code_retention_days">{{ t('admin.systemSettings.cleanup.verifyCodeRetention') }}</UiLabel>
              <UiInput
                id="verify_code_retention_days"
                v-model.number="cleanupForm.verify_code_retention_days"
                type="number"
                min="1"
                max="90"
              />
              <p class="text-xs text-muted-foreground">
                {{ t('admin.systemSettings.cleanup.verifyCodeRetentionHint') }}
              </p>
            </div>

            <div class="space-y-2">
              <UiLabel for="api_usage_retention_days">{{ t('admin.systemSettings.cleanup.apiUsageRetention') }}</UiLabel>
              <UiInput
                id="api_usage_retention_days"
                v-model.number="cleanupForm.api_usage_retention_days"
                type="number"
                min="7"
                max="365"
              />
              <p class="text-xs text-muted-foreground">
                {{ t('admin.systemSettings.cleanup.apiUsageRetentionHint') }}
              </p>
            </div>
          </div>

          <div class="grid gap-4 md:grid-cols-2">
            <div class="space-y-2">
              <UiLabel for="webhook_log_retention_days">{{ t('admin.systemSettings.cleanup.webhookLogRetention') }}</UiLabel>
              <UiInput
                id="webhook_log_retention_days"
                v-model.number="cleanupForm.webhook_log_retention_days"
                type="number"
                min="7"
                max="365"
              />
              <p class="text-xs text-muted-foreground">
                {{ t('admin.systemSettings.cleanup.webhookLogRetentionHint') }}
              </p>
            </div>

            <div class="space-y-2">
              <UiLabel for="device_session_retention_days">{{ t('admin.systemSettings.cleanup.deviceSessionRetention') }}</UiLabel>
              <UiInput
                id="device_session_retention_days"
                v-model.number="cleanupForm.device_session_retention_days"
                type="number"
                min="1"
                max="90"
              />
              <p class="text-xs text-muted-foreground">
                {{ t('admin.systemSettings.cleanup.deviceSessionRetentionHint') }}
              </p>
            </div>
          </div>

          <div class="flex items-center gap-4 border-t pt-4">
            <UiButton :disabled="cleanupLoading" @click="saveCleanupSettings">
              <Loader2 v-if="cleanupLoading" class="mr-2 h-4 w-4 animate-spin" />
              {{ t('admin.systemSettings.cleanup.saveCleanupSettings') }}
            </UiButton>
            <UiButton variant="outline" :disabled="manualCleanupLoading" @click="runManualCleanup">
              <Loader2 v-if="manualCleanupLoading" class="mr-2 h-4 w-4 animate-spin" />
              <Trash2 v-else class="mr-2 h-4 w-4" />
              {{ t('admin.systemSettings.cleanup.runManualCleanup') }}
            </UiButton>
          </div>
        </UiCardContent>
      </UiCard>

      <div class="flex justify-end">
        <UiButton :disabled="saving" @click="saveSettings">
          <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
          {{ t('admin.systemSettings.saveSettings') }}
        </UiButton>
      </div>
    </div>
  </BasicPage>
</template>
