<script setup lang="ts">
import { Box, Check, CheckCircle, Coins, CreditCard, Eye, Gift, Info, Loader2, Plus, Repeat, Upload, X } 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'

const router = useRouter()

const API_BASE = 'http://localhost:8080/api/v1'
const loading = ref(false)
const showSuccessDialog = ref(false)
const createdAppId = ref<number | null>(null)

const formData = ref({
  name: '',
  description: '',
  billing_type: 'free' as 'free' | 'subscription' | 'balance',
  iconFile: null as File | null,
  iconPreview: '',
})

const billingOptions = [
  { value: 'free', label: '免费模式', desc: '用户无需付费', iconComponent: Gift },
  { value: 'subscription', label: '订阅模式', desc: '按周期付费订阅', iconComponent: Repeat },
  { value: 'balance', label: '余额模式', desc: '按使用量计费', iconComponent: Coins },
]

const selectedBilling = computed(() => {
  return billingOptions.find(b => b.value === formData.value.billing_type)
})

function handleIconUpload(event: Event) {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file) {
    formData.value.iconFile = file
    formData.value.iconPreview = URL.createObjectURL(file)
  }
}

function clearIcon() {
  formData.value.iconFile = null
  formData.value.iconPreview = ''
}

async function handleCreate() {
  if (!formData.value.name.trim()) {
    toast.error('请输入应用名称')
    return
  }

  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const formDataToSend = new FormData()
    formDataToSend.append('name', formData.value.name)
    formDataToSend.append('description', formData.value.description)
    formDataToSend.append('billing_type', formData.value.billing_type)
    formDataToSend.append('login_policy', 'loose')
    formDataToSend.append('encrypt_type', 'none')
    formDataToSend.append('bind_type', 'none')
    formDataToSend.append('max_devices', '1')
    formDataToSend.append('multi_open_mode', 'forbidden')
    formDataToSend.append('max_instances', '1')
    formDataToSend.append('heartbeat_interval', '60')
    formDataToSend.append('heartbeat_timeout', '300')
    formDataToSend.append('max_attempts', '5')
    formDataToSend.append('lock_duration', '30')
    formDataToSend.append('allow_register', 'true')
    formDataToSend.append('enable_login_verify', 'false')
    formDataToSend.append('enable_register_verify', 'false')
    formDataToSend.append('enable_trial', 'false')
    formDataToSend.append('trial_balance', '0')
    formDataToSend.append('enable_free_period', 'false')
    formDataToSend.append('status', 'active')

    if (formData.value.iconFile) {
      formDataToSend.append('icon', formData.value.iconFile)
    }

    const response = await fetch(`${API_BASE}/dev/applications`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${token}`,
      },
      body: formDataToSend,
    })

    const data = await response.json()
    if (data.code === 200) {
      createdAppId.value = data.data?.application?.id || data.data?.id
      showSuccessDialog.value = true
    }
    else {
      toast.error(data.message || '创建失败')
    }
  }
  catch (error) {
    console.error('创建应用失败:', error)
    toast.error('创建失败')
  }
  finally {
    loading.value = false
  }
}

function goToSettings() {
  showSuccessDialog.value = false
  router.push(`/admin/applications/${createdAppId.value}/settings`)
}

function goToAppList() {
  showSuccessDialog.value = false
  router.push('/admin/applications')
}
</script>

<template>
  <BasicPage
    title="创建应用"
    description="创建一个新的应用，快速开始您的业务"
    :breadcrumbs="[
      { title: '应用管理', href: '/admin/applications' },
      { 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">
                <Box 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="loading"
                  />
                </div>

                <div class="space-y-2">
                  <UiLabel>应用图标</UiLabel>
                  <div class="flex items-center gap-3">
                    <div v-if="formData.iconPreview" class="relative group">
                      <img
                        :src="formData.iconPreview"
                        alt="应用图标"
                        class="w-12 h-12 rounded-lg object-cover border"
                      >
                      <button
                        type="button"
                        class="absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                        @click="clearIcon"
                      >
                        <X class="h-3 w-3" />
                      </button>
                    </div>
                    <label
                      for="appIcon"
                      class="flex items-center justify-center h-12 px-4 border-2 border-dashed rounded-lg cursor-pointer hover:bg-accent/50 transition-colors"
                    >
                      <Upload class="w-4 h-4 mr-2 text-muted-foreground" />
                      <span class="text-sm text-muted-foreground">
                        {{ formData.iconPreview ? '更换' : '上传' }}
                      </span>
                      <input
                        id="appIcon"
                        type="file"
                        accept="image/*"
                        class="hidden"
                        @change="handleIconUpload"
                      >
                    </label>
                  </div>
                </div>
              </div>

              <div class="space-y-2">
                <UiLabel for="description">应用描述</UiLabel>
                <UiTextarea
                  id="description"
                  v-model="formData.description"
                  placeholder="请输入应用描述（可选）"
                  rows="3"
                  :disabled="loading"
                />
              </div>
            </UiCardContent>
          </UiCard>

          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <CreditCard class="size-5" />
                运营模式
              </UiCardTitle>
              <UiCardDescription>选择应用的计费方式</UiCardDescription>
            </UiCardHeader>
            <UiCardContent>
              <div class="grid gap-3 md:grid-cols-3">
                <div
                  v-for="option in billingOptions"
                  :key="option.value"
                  class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                  :class="formData.billing_type === option.value ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                  @click="formData.billing_type = option.value as any"
                >
                  <div
                    class="flex items-center justify-center w-10 h-10 rounded-lg shrink-0"
                    :class="formData.billing_type === option.value ? 'bg-primary text-primary-foreground' : 'bg-muted'"
                  >
                    <component :is="option.iconComponent" class="size-5" />
                  </div>
                  <div class="flex-1 min-w-0">
                    <div class="flex items-center gap-2">
                      <p class="font-medium">
                        {{ option.label }}
                      </p>
                      <Check v-if="formData.billing_type === option.value" class="size-4 text-primary" />
                    </div>
                    <p class="text-sm text-muted-foreground">
                      {{ option.desc }}
                    </p>
                  </div>
                </div>
              </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="flex items-center gap-3 pb-4 border-b">
                <div
                  class="flex items-center justify-center w-12 h-12 rounded-lg bg-muted text-muted-foreground overflow-hidden"
                >
                  <img
                    v-if="formData.iconPreview"
                    :src="formData.iconPreview"
                    alt="图标"
                    class="w-full h-full object-cover"
                  >
                  <Box v-else class="size-6" />
                </div>
                <div class="flex-1 min-w-0">
                  <p class="font-medium truncate">
                    {{ formData.name || '未命名应用' }}
                  </p>
                  <p class="text-sm text-muted-foreground">
                    {{ selectedBilling?.label || '免费模式' }}
                  </p>
                </div>
              </div>

              <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>{{ selectedBilling?.label || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">应用描述</span>
                  <span class="truncate max-w-[120px]">{{ formData.description || '-' }}</span>
                </div>
              </div>
            </UiCardContent>
          </UiCard>

          <UiCard>
            <UiCardContent class="pt-6">
              <div class="flex flex-col gap-3">
                <UiButton
                  class="w-full"
                  size="lg"
                  :disabled="loading || !formData.name"
                  @click="handleCreate"
                >
                  <Loader2 v-if="loading" 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>

          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2 text-sm">
                <Info class="size-4" />
                提示
              </UiCardTitle>
            </UiCardHeader>
            <UiCardContent>
              <ul class="text-sm text-muted-foreground space-y-2">
                <li class="flex items-start gap-2">
                  <Check class="size-4 text-green-500 mt-0.5 shrink-0" />
                  创建后可在设置页面配置更多选项
                </li>
                <li class="flex items-start gap-2">
                  <Check class="size-4 text-green-500 mt-0.5 shrink-0" />
                  支持配置验证方式、安全策略等
                </li>
                <li class="flex items-start gap-2">
                  <Check class="size-4 text-green-500 mt-0.5 shrink-0" />
                  可随时修改应用信息和设置
                </li>
              </ul>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>

    <UiDialog v-model:open="showSuccessDialog">
      <UiDialogContent class="sm:max-w-md">
        <UiDialogHeader>
          <UiDialogTitle class="flex items-center gap-2">
            <CheckCircle class="h-5 w-5 text-green-500" />
            应用创建成功
          </UiDialogTitle>
          <UiDialogDescription>
            您的应用已创建成功，接下来您可以配置更多设置。
          </UiDialogDescription>
        </UiDialogHeader>
        <div class="space-y-4 py-4">
          <div class="p-4 rounded-lg bg-muted/50 space-y-3">
            <p class="text-sm font-medium">
              推荐配置：
            </p>
            <ul class="text-sm text-muted-foreground space-y-2">
              <li class="flex items-center gap-2">
                <Check class="h-4 w-4 text-green-500" />
                配置验证方式（邮箱/短信验证）
              </li>
              <li class="flex items-center gap-2">
                <Check class="h-4 w-4 text-green-500" />
                设置安全策略（加密、绑定）
              </li>
              <li class="flex items-center gap-2">
                <Check class="h-4 w-4 text-green-500" />
                上传应用版本文件
              </li>
            </ul>
          </div>
        </div>
        <UiDialogFooter class="flex-col sm:flex-row gap-2">
          <UiButton variant="outline" @click="goToAppList">
            稍后配置
          </UiButton>
          <UiButton @click="goToSettings">
            前往设置
          </UiButton>
        </UiDialogFooter>
      </UiDialogContent>
    </UiDialog>
  </BasicPage>
</template>
