<script setup lang="ts">
import { Eye, Loader2, Mail, Save } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

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

const route = useRoute()
const router = useRouter()

const loading = ref(true)
const saving = ref(false)

const formData = ref({
  name: '',
  smtp_host: '',
  smtp_port: 587,
  smtp_user: '',
  smtp_password: '',
  smtp_from: '',
  smtp_from_name: '',
  encryption: 'tls' as 'none' | 'ssl' | 'tls',
  status: 'active' as 'active' | 'inactive',
  remark: '',
})

const encryptionOptions = [
  { value: 'none', label: '无加密', desc: '不使用加密连接' },
  { value: 'ssl', label: 'SSL', desc: '使用SSL加密（端口465）' },
  { value: 'tls', label: 'TLS', desc: '使用TLS加密（端口587）' },
]

const selectedEncryption = computed(() => {
  return encryptionOptions.find(e => e.value === formData.value.encryption)
})

async function fetchEmailConfig() {
  loading.value = true
  try {
    const data = await api.get(`/dev/email-configs/${route.params.id}`)
    if (data) {
      formData.value = {
        name: data.name,
        smtp_host: data.smtp_host,
        smtp_port: data.smtp_port,
        smtp_user: data.smtp_user,
        smtp_password: data.smtp_password || '',
        smtp_from: data.smtp_from,
        smtp_from_name: data.smtp_from_name || '',
        encryption: data.encryption || 'tls',
        status: data.status,
        remark: data.remark || '',
      }
    }
  }
  catch (error: any) {
    console.error('加载邮箱配置失败:', error)
    toast.error(error.message || '加载失败')
    router.push('/admin/email-settings')
  }
  finally {
    loading.value = false
  }
}

async function handleSubmit() {
  if (!formData.value.name) {
    toast.error('请输入配置名称')
    return
  }
  if (!formData.value.smtp_host) {
    toast.error('请输入SMTP服务器地址')
    return
  }

  saving.value = true
  try {
    await api.put(`/dev/email-configs/${route.params.id}`, formData.value)
    toast.success('更新成功')
    router.push('/admin/email-settings')
  }
  catch (error: any) {
    console.error('更新邮箱配置失败:', error)
    toast.error(error.message || '更新失败')
  }
  finally {
    saving.value = false
  }
}

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

<template>
  <BasicPage
    title="编辑邮箱配置"
    description="修改SMTP邮箱服务配置"
    :breadcrumbs="[
      { title: '邮箱配置', href: '/admin/email-settings' },
      { title: '编辑配置' },
    ]"
    sticky
  >
    <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="grid gap-6 lg:grid-cols-3">
        <div class="lg:col-span-2 space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Mail class="size-5" />
                基本配置
              </UiCardTitle>
              <UiCardDescription>修改SMTP服务器的基本信息</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="grid gap-4 md:grid-cols-2">
                <div class="space-y-2">
                  <UiLabel for="name">
                    配置名称 <span class="text-destructive">*</span>
                  </UiLabel>
                  <UiInput
                    id="name"
                    v-model="formData.name"
                    placeholder="如：主邮箱、通知邮箱"
                    :disabled="saving"
                  />
                </div>

                <div class="space-y-2">
                  <UiLabel for="smtp_host">
                    SMTP服务器 <span class="text-destructive">*</span>
                  </UiLabel>
                  <UiInput
                    id="smtp_host"
                    v-model="formData.smtp_host"
                    placeholder="smtp.example.com"
                    :disabled="saving"
                  />
                </div>

                <div class="space-y-2">
                  <UiLabel for="smtp_port">端口</UiLabel>
                  <UiInput
                    id="smtp_port"
                    v-model.number="formData.smtp_port"
                    type="number"
                    placeholder="587"
                    :disabled="saving"
                  />
                </div>

                <div class="space-y-2">
                  <UiLabel for="smtp_user">
                    用户名 <span class="text-destructive">*</span>
                  </UiLabel>
                  <UiInput
                    id="smtp_user"
                    v-model="formData.smtp_user"
                    placeholder="user@example.com"
                    :disabled="saving"
                  />
                </div>

                <div class="space-y-2">
                  <UiLabel for="smtp_password">密码</UiLabel>
                  <UiInput
                    id="smtp_password"
                    v-model="formData.smtp_password"
                    type="password"
                    placeholder="••••••••"
                    :disabled="saving"
                  />
                </div>

                <div class="space-y-2">
                  <UiLabel for="smtp_from">
                    发件人地址 <span class="text-destructive">*</span>
                  </UiLabel>
                  <UiInput
                    id="smtp_from"
                    v-model="formData.smtp_from"
                    placeholder="noreply@example.com"
                    :disabled="saving"
                  />
                </div>

                <div class="space-y-2">
                  <UiLabel for="smtp_from_name">发件人名称</UiLabel>
                  <UiInput
                    id="smtp_from_name"
                    v-model="formData.smtp_from_name"
                    placeholder="系统通知"
                    :disabled="saving"
                  />
                </div>
              </div>

              <div class="space-y-2">
                <UiLabel>加密方式</UiLabel>
                <UiSelect v-model="formData.encryption" :disabled="saving">
                  <UiSelectTrigger>
                    <UiSelectValue placeholder="选择加密方式" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem v-for="enc in encryptionOptions" :key="enc.value" :value="enc.value">
                      <div class="flex flex-col">
                        <span>{{ enc.label }}</span>
                      </div>
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
                <p class="text-xs text-muted-foreground">{{ selectedEncryption?.desc }}</p>
              </div>

              <div class="space-y-2">
                <UiLabel for="remark">备注</UiLabel>
                <UiInput
                  id="remark"
                  v-model="formData.remark"
                  placeholder="备注信息（可选）"
                  :disabled="saving"
                />
              </div>

              <div class="flex items-center justify-between rounded-lg border p-4">
                <div class="space-y-0.5">
                  <UiLabel class="text-base">
                    启用状态
                  </UiLabel>
                  <p class="text-sm text-muted-foreground">
                    启用后该邮箱配置可用于发送邮件
                  </p>
                </div>
                <UiSwitch
                  :checked="formData.status === 'active'"
                  :disabled="saving"
                  @update:checked="formData.status = $event ? 'active' : 'inactive'"
                />
              </div>
            </UiCardContent>
          </UiCard>
        </div>

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Eye class="size-5" />
                预览
              </UiCardTitle>
            </UiCardHeader>
            <UiCardContent class="space-y-4">
              <div class="space-y-3">
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">配置名称</span>
                  <span class="truncate max-w-[120px]">{{ formData.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">SMTP服务器</span>
                  <span class="truncate max-w-[120px]">{{ formData.smtp_host || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">端口</span>
                  <span>{{ formData.smtp_port }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">用户名</span>
                  <span class="truncate max-w-[120px]">{{ formData.smtp_user || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">发件人</span>
                  <span class="truncate max-w-[120px]">{{ formData.smtp_from_name ? `${formData.smtp_from_name} <${formData.smtp_from}>` : formData.smtp_from || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">加密方式</span>
                  <span>{{ selectedEncryption?.label || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">状态</span>
                  <span>{{ formData.status === 'active' ? '启用' : '禁用' }}</span>
                </div>
              </div>
            </UiCardContent>
          </UiCard>

          <UiCard>
            <UiCardContent class="pt-6">
              <div class="flex flex-col gap-3">
                <UiButton
                  class="w-full"
                  size="lg"
                  :disabled="saving || !formData.name || !formData.smtp_host"
                  @click="handleSubmit"
                >
                  <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
                  <Save v-else class="mr-2 h-4 w-4" />
                  保存修改
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  取消
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
