<script setup lang="ts">
import { Cloud, Eye, Loader2, Plus, Settings, Smartphone } 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: '',
  type: 'aliyun' as 'aliyun' | 'tencent' | 'other',
  config: '',
  status: 'active' as 'active' | 'inactive',
  remark: '',
})

const typeOptions = [
  { value: 'aliyun', label: '阿里云', desc: '阿里云短信服务', icon: Cloud },
  { value: 'tencent', label: '腾讯云', desc: '腾讯云短信服务', icon: Cloud },
  { value: 'other', label: '其他', desc: '其他短信服务商', icon: Settings },
]

const selectedType = computed(() => {
  return typeOptions.find(t => t.value === formData.value.type)
})

const configPlaceholder = computed(() => {
  switch (formData.value.type) {
    case 'aliyun':
      return `{
  "access_key_id": "您的AccessKeyID",
  "access_key_secret": "您的AccessKeySecret",
  "sign_name": "签名名称",
  "template_code": "模板CODE"
}`
    case 'tencent':
      return `{
  "secret_id": "您的SecretId",
  "secret_key": "您的SecretKey",
  "sdk_app_id": "应用ID",
  "sign_name": "签名名称",
  "template_id": "模板ID"
}`
    default:
      return `{
  "api_url": "短信服务商API地址",
  "api_key": "API密钥",
  "其他参数": "根据服务商文档配置"
}`
  }
})

async function handleSubmit() {
  if (!formData.value.name) {
    toast.error('请输入配置名称')
    return
  }
  if (!formData.value.type) {
    toast.error('请选择短信类型')
    return
  }

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

<template>
  <BasicPage
    title="添加短信配置"
    description="配置新的短信服务"
    :breadcrumbs="[
      { title: '短信配置', href: '/admin/sms-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">
                <Smartphone class="size-5" />
                基本配置
              </UiCardTitle>
              <UiCardDescription>填写短信服务的基本信息</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>
                    短信类型 <span class="text-destructive">*</span>
                  </UiLabel>
                  <UiSelect v-model="formData.type" :disabled="saving">
                    <UiSelectTrigger>
                      <UiSelectValue placeholder="选择短信类型" />
                    </UiSelectTrigger>
                    <UiSelectContent>
                      <UiSelectItem v-for="type in typeOptions" :key="type.value" :value="type.value">
                        <div class="flex items-center gap-2">
                          <component :is="type.icon" class="size-4" />
                          <span>{{ type.label }}</span>
                        </div>
                      </UiSelectItem>
                    </UiSelectContent>
                  </UiSelect>
                </div>
              </div>

              <div class="space-y-2">
                <UiLabel for="config">配置信息</UiLabel>
                <textarea
                  id="config"
                  v-model="formData.config"
                  class="flex min-h-[150px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 font-mono"
                  :placeholder="configPlaceholder"
                  :disabled="saving"
                />
                <p class="text-xs text-muted-foreground">
                  JSON格式的配置信息，根据所选短信服务商填写对应参数
                </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">短信类型</span>
                  <span>{{ selectedType?.label || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">状态</span>
                  <span>{{ formData.status === 'active' ? '启用' : '禁用' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">备注</span>
                  <span class="truncate max-w-[120px]">{{ formData.remark || '-' }}</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"
                  @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>
