<script setup lang="ts">
import { Check, Info, Loader2, Settings2 } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
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 { t } = useI18n()

interface Application {
  id: number
  name: string
}

const saving = ref(false)
const applications = ref<Application[]>([])

const form = ref({
  name: '',
  application_id: '',
  url: '',
  secret_key: '',
  events: [] as string[],
  retry_count: 3,
  timeout: 10,
  enabled: true,
})

const availableEvents = computed(() => [
  { value: 'user.registered', label: t('admin.extension.webhooks.events.userRegistered') },
  { value: 'user.login', label: t('admin.extension.webhooks.events.userLogin') },
  { value: 'user.recharged', label: t('admin.extension.webhooks.events.userRecharged') },
  { value: 'user.expired', label: t('admin.extension.webhooks.events.userExpired') },
  { value: 'card.used', label: t('admin.extension.webhooks.events.cardUsed') },
  { value: 'card.expired', label: t('admin.extension.webhooks.events.cardExpired') },
  { value: 'abnormal.detected', label: t('admin.extension.webhooks.events.abnormalDetected') },
])

const filteredApplications = computed(() => {
  return applications.value.map(app => ({
    label: app.name,
    value: String(app.id),
  }))
})

const selectedApplication = computed(() => {
  if (form.value.application_id) {
    return applications.value.find(app => String(app.id) === form.value.application_id)
  }
  return null
})

async function fetchApplications() {
  try {
    const data = await api.get<{ applications: Application[] }>('/dev/applications')
    applications.value = Array.isArray(data?.applications) ? data.applications : []
  }
  catch (error) {
    console.error('获取应用列表失败:', error)
  }
}

function toggleEvent(event: string) {
  const index = form.value.events.indexOf(event)
  if (index > -1) {
    form.value.events.splice(index, 1)
  }
  else {
    form.value.events.push(event)
  }
}

async function handleSubmit() {
  if (!form.value.name) {
    toast.error(t('admin.extension.webhooks.create.nameRequired'))
    return
  }
  if (!form.value.application_id) {
    toast.error(t('admin.extension.webhooks.create.selectAppRequired'))
    return
  }
  if (!form.value.url) {
    toast.error(t('admin.extension.webhooks.create.urlRequired'))
    return
  }
  if (form.value.events.length === 0) {
    toast.error(t('admin.extension.webhooks.create.eventsRequired'))
    return
  }

  saving.value = true
  try {
    await api.post('/dev/extension/webhooks', {
      name: form.value.name,
      application_id: Number.parseInt(form.value.application_id),
      url: form.value.url,
      secret_key: form.value.secret_key,
      events: form.value.events,
      retry_count: form.value.retry_count,
      timeout: form.value.timeout,
      enabled: form.value.enabled,
    })
    toast.success(t('admin.extension.webhooks.create.submitSuccess'))
    router.push('/admin/extension')
  }
  catch (error: any) {
    console.error('创建Webhook失败:', error)
    toast.error(error.message || t('admin.extension.webhooks.create.submitFailed'))
  }
  finally {
    saving.value = false
  }
}

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

<template>
  <BasicPage
    :title="t('admin.extension.webhooks.create.title')"
    :description="t('admin.extension.webhooks.create.description')"
    :breadcrumbs="[
      { title: t('admin.extension.title'), href: '/admin/extension' },
      { title: t('admin.extension.webhooks.create.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">
                <Settings2 class="size-5" />
                {{ t('admin.extension.webhooks.create.title') }}
              </UiCardTitle>
              <UiCardDescription>{{ t('admin.extension.webhooks.create.description') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel for="name">
                  {{ t('admin.extension.webhooks.create.name') }} *
                </UiLabel>
                <UiInput
                  id="name"
                  v-model="form.name"
                  :placeholder="t('admin.extension.webhooks.create.namePlaceholder')"
                />
              </div>

              <div class="space-y-2">
                <UiLabel for="application">
                  {{ t('admin.extension.webhooks.create.application') }} *
                </UiLabel>
                <UiSelect v-model="form.application_id">
                  <UiSelectTrigger>
                    <UiSelectValue :placeholder="t('admin.extension.webhooks.create.selectAppPlaceholder')" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem v-for="app in filteredApplications" :key="app.value" :value="app.value">
                      {{ app.label }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>

              <div class="space-y-2">
                <UiLabel for="url">
                  {{ t('admin.extension.webhooks.create.url') }} *
                </UiLabel>
                <UiInput
                  id="url"
                  v-model="form.url"
                  :placeholder="t('admin.extension.webhooks.create.urlPlaceholder')"
                />
              </div>

              <div class="space-y-2">
                <UiLabel for="secret_key">
                  {{ t('admin.extension.webhooks.create.secretKey') }}
                </UiLabel>
                <UiInput
                  id="secret_key"
                  v-model="form.secret_key"
                  :placeholder="t('admin.extension.webhooks.create.secretKeyPlaceholder')"
                />
              </div>

              <div class="space-y-2">
                <UiLabel>{{ t('admin.extension.webhooks.create.events') }} *</UiLabel>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-2">
                  <div
                    v-for="event in availableEvents"
                    :key="event.value"
                    class="flex items-center space-x-2 p-3 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors"
                    :class="{ 'bg-primary/10 border-primary': form.events.includes(event.value) }"
                    @click="toggleEvent(event.value)"
                  >
                    <UiCheckbox
                      :checked="form.events.includes(event.value)"
                      @update:checked="toggleEvent(event.value)"
                    />
                    <span class="text-sm">{{ event.label }}</span>
                  </div>
                </div>
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="space-y-2">
                  <UiLabel for="retry_count">
                    {{ t('admin.extension.webhooks.create.retryCount') }}
                  </UiLabel>
                  <UiInput
                    id="retry_count"
                    v-model.number="form.retry_count"
                    type="number"
                    min="0"
                    max="10"
                    :placeholder="t('admin.extension.webhooks.create.retryCountPlaceholder')"
                  />
                </div>

                <div class="space-y-2">
                  <UiLabel for="timeout">
                    {{ t('admin.extension.webhooks.create.timeout') }}
                  </UiLabel>
                  <UiInput
                    id="timeout"
                    v-model.number="form.timeout"
                    type="number"
                    min="1"
                    max="60"
                    :placeholder="t('admin.extension.webhooks.create.timeoutPlaceholder')"
                  />
                </div>
              </div>

              <div class="flex items-center space-x-2">
                <UiSwitch id="enabled" v-model:checked="form.enabled" />
                <UiLabel for="enabled">
                  {{ t('admin.extension.webhooks.create.enabled') }}
                </UiLabel>
              </div>
            </UiCardContent>
          </UiCard>
        </div>

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Info class="size-5" />
                {{ t('admin.extension.webhooks.create.preview') || '预览' }}
              </UiCardTitle>
            </UiCardHeader>
            <UiCardContent class="space-y-4">
              <div class="space-y-3">
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.extension.webhooks.create.name') }}</span>
                  <span>{{ form.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.extension.webhooks.create.application') }}</span>
                  <span>{{ selectedApplication?.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.extension.webhooks.create.events') }}</span>
                  <span>{{ form.events.length }} {{ t('admin.extension.webhooks.create.selected') || '已选择' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.extension.webhooks.create.retryCount') }}</span>
                  <span>{{ form.retry_count }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.extension.webhooks.create.timeout') }}</span>
                  <span>{{ form.timeout }}s</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 || !form.name || !form.application_id || !form.url || form.events.length === 0"
                  @click="handleSubmit"
                >
                  <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
                  <Check v-else class="mr-2 h-4 w-4" />
                  {{ t('admin.extension.webhooks.create.submitBtn') }}
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  {{ t('admin.extension.webhooks.create.cancelBtn') }}
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
