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

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

const router = useRouter()

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 handleSubmit() {
  if (!formData.value.name) {
    toast.error('请输入配置名称')
    return
  }
  if (!formData.value.smtp_host) {
    toast.error('请输入SMTP服务器地址')
    return
  }
  if (!formData.value.smtp_user) {
    toast.error('请输入SMTP用户名')
    return
  }
  if (!formData.value.smtp_from) {
    toast.error('请输入发件人地址')
    return
  }

  saving.value = true
  try {
    await api.post('/dev/email-configs', formData.value)
    toast.success('创建成功')
    router.push('/admin/email-settings')
  }
  catch (error: any) {
    console.error('创建邮箱配置失败:', error)
    toast.error(error.message || '创建失败')
  }
  finally {
    saving.value = false
  }
}
</script>

<template>
  <BasicPage
    title="添加邮箱配置"
    description="配置新的SMTP邮箱服务"
    :breadcrumbs="[
      { title: '邮箱配置', href: '/admin/email-settings' },
      { title: '添加配置' },
    ]"
    sticky
  >
    <div 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" />
                  <Plus 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>
