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

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

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,
})

async function loadSettings() {
  loading.value = true
  try {
    const data = await api.get('/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('加载设置失败')
  }
  finally {
    loading.value = false
  }
}

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('保存成功')
    updateGlobalSettings()
  }
  catch (error) {
    toast.error('保存失败')
  }
  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 }))
}

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('/dev/system-settings/upload', formData)
    basicForm.value.site_logo = data.url
    toast.success('Logo上传成功')
  }
  catch (error: any) {
    toast.error(error.message || '上传失败')
  }
  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('/dev/system-settings/upload', formData)
    basicForm.value.site_favicon = data.url
    toast.success('图标上传成功')
  }
  catch (error: any) {
    toast.error(error.message || '上传失败')
  }
  finally {
    uploadingFavicon.value = false
    target.value = ''
  }
}

const tabs = [
  { id: 'basic', label: '基本设置', icon: Settings },
  { id: 'security', label: '安全设置', icon: Shield },
  { id: 'backup', label: '备份设置', icon: Database },
  { id: 'feature', label: '功能设置', icon: ToggleLeft },
  { id: 'notification', label: '通知设置', icon: Bell },
]

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

<template>
  <BasicPage title="系统设置" 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>基本设置</UiCardTitle>
          <UiCardDescription>配置网站基本信息</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-6">
          <div class="space-y-2">
            <UiLabel for="site_name">网站名称</UiLabel>
            <UiInput id="site_name" v-model="basicForm.site_name" placeholder="请输入网站名称" />
          </div>

          <div class="space-y-2">
            <UiLabel>网站Logo</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" />
                    上传Logo
                  </UiButton>
                  <span class="text-xs text-muted-foreground">支持 JPG、PNG、SVG 格式</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 = ''"
                  >
                    移除
                  </UiButton>
                </div>
              </div>
            </div>
          </div>

          <div class="space-y-2">
            <UiLabel>网站图标 (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" />
                    上传图标
                  </UiButton>
                  <span class="text-xs text-muted-foreground">推荐 32x32 或 64x64 像素的 ICO/PNG</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 = ''"
                  >
                    移除
                  </UiButton>
                </div>
              </div>
            </div>
          </div>

          <div class="space-y-2">
            <UiLabel for="site_footer">页脚信息</UiLabel>
            <UiInput id="site_footer" v-model="basicForm.site_footer" placeholder="请输入页脚信息" />
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard v-show="activeTab === 'security'">
        <UiCardHeader>
          <UiCardTitle>安全设置</UiCardTitle>
          <UiCardDescription>配置系统安全相关选项</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-6">
          <div class="flex items-center justify-between">
            <div class="space-y-0.5">
              <UiLabel>登录验证码</UiLabel>
              <p class="text-sm text-muted-foreground">
                启用后登录时需要输入验证码
              </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">登录失败锁定次数</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">
                连续失败多少次后锁定账户
              </p>
            </div>

            <div class="space-y-2">
              <UiLabel for="login_fail_lock_minutes">锁定时长（分钟）</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">
                账户锁定持续时间
              </p>
            </div>
          </div>

          <div class="grid gap-4 md:grid-cols-2">
            <div class="space-y-2">
              <UiLabel for="password_min_length">密码最小长度</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">
                用户密码最小字符数
              </p>
            </div>

            <div class="space-y-2">
              <UiLabel for="session_timeout">会话超时（小时）</UiLabel>
              <UiInput
                id="session_timeout"
                v-model.number="securityForm.session_timeout"
                type="number"
                min="1"
                max="720"
              />
              <p class="text-xs text-muted-foreground">
                用户登录会话有效期
              </p>
            </div>
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard v-show="activeTab === 'backup'">
        <UiCardHeader>
          <UiCardTitle>备份设置</UiCardTitle>
          <UiCardDescription>配置数据库自动备份</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-6">
          <div class="flex items-center justify-between">
            <div class="space-y-0.5">
              <UiLabel>启用自动备份</UiLabel>
              <p class="text-sm text-muted-foreground">
                定时自动备份数据库
              </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">备份间隔（小时）</UiLabel>
              <UiInput
                id="backup_interval"
                v-model.number="backupForm.backup_interval"
                type="number"
                min="1"
                max="168"
              />
              <p class="text-xs text-muted-foreground">
                每隔多少小时备份一次
              </p>
            </div>

            <div class="space-y-2">
              <UiLabel for="backup_retention">保留天数</UiLabel>
              <UiInput
                id="backup_retention"
                v-model.number="backupForm.backup_retention"
                type="number"
                min="1"
                max="90"
              />
              <p class="text-xs text-muted-foreground">
                备份文件保留多少天
              </p>
            </div>
          </div>

          <div class="space-y-2">
            <UiLabel for="backup_storage_type">存储位置</UiLabel>
            <UiSelect v-model="backupForm.backup_storage_type">
              <UiSelectTrigger>
                <UiSelectValue placeholder="选择存储位置" />
              </UiSelectTrigger>
              <UiSelectContent>
                <UiSelectItem value="local">
                  本地存储
                </UiSelectItem>
                <UiSelectItem value="s3">
                  S3存储
                </UiSelectItem>
                <UiSelectItem value="webdav">
                  WebDAV
                </UiSelectItem>
                <UiSelectItem value="ftp">
                  FTP
                </UiSelectItem>
                <UiSelectItem value="sftp">
                  SFTP
                </UiSelectItem>
              </UiSelectContent>
            </UiSelect>
            <p class="text-xs text-muted-foreground">
              备份文件存储位置，可在存储管理中配置
            </p>
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard v-show="activeTab === 'feature'">
        <UiCardHeader>
          <UiCardTitle>功能设置</UiCardTitle>
          <UiCardDescription>配置系统功能开关</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-6">
          <div class="flex items-center justify-between">
            <div class="space-y-0.5">
              <UiLabel>工单系统</UiLabel>
              <p class="text-sm text-muted-foreground">
                启用后用户可以提交工单
              </p>
            </div>
            <UiSwitch v-model="featureForm.enable_ticket_system" />
          </div>

          <div class="flex items-center justify-between">
            <div class="space-y-0.5">
              <UiLabel>多语言支持</UiLabel>
              <p class="text-sm text-muted-foreground">
                启用后用户可以切换语言
              </p>
            </div>
            <UiSwitch v-model="featureForm.enable_multi_lang" />
          </div>

          <div class="space-y-2">
            <UiLabel for="default_theme">默认颜色模式</UiLabel>
            <UiSelect v-model="featureForm.default_theme">
              <UiSelectTrigger>
                <UiSelectValue placeholder="选择默认颜色模式" />
              </UiSelectTrigger>
              <UiSelectContent>
                <UiSelectItem value="system">
                  跟随系统
                </UiSelectItem>
                <UiSelectItem value="light">
                  浅色模式
                </UiSelectItem>
                <UiSelectItem value="dark">
                  深色模式
                </UiSelectItem>
              </UiSelectContent>
            </UiSelect>
            <p class="text-xs text-muted-foreground">
              新用户默认的颜色模式
            </p>
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard v-show="activeTab === 'notification'">
        <UiCardHeader>
          <UiCardTitle>通知设置</UiCardTitle>
          <UiCardDescription>配置系统通知选项</UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-6">
          <div class="flex items-center justify-between">
            <div class="space-y-0.5">
              <UiLabel>启用邮件通知</UiLabel>
              <p class="text-sm text-muted-foreground">
                启用后系统将发送邮件通知
              </p>
            </div>
            <UiSwitch v-model="notificationForm.enable_notification" />
          </div>

          <div class="space-y-2">
            <UiLabel for="admin_notify_email">管理员通知邮箱</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">
              接收系统通知的管理员邮箱
            </p>
          </div>

          <div class="space-y-4">
            <UiLabel>通知事件</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">
                    异常登录通知
                  </p>
                  <p class="text-xs text-muted-foreground">
                    检测到异常登录时发送通知
                  </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">
                    充值通知
                  </p>
                  <p class="text-xs text-muted-foreground">
                    用户充值成功时发送通知
                  </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">
                    工单通知
                  </p>
                  <p class="text-xs text-muted-foreground">
                    新工单提交时发送通知
                  </p>
                </div>
                <UiSwitch v-model="notificationForm.notify_on_ticket" />
              </div>
            </div>
          </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" />
          保存设置
        </UiButton>
      </div>
    </div>
  </BasicPage>
</template>
