<script setup lang="ts">
import { Loader2, Receipt, Settings2, Sparkles } 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 CardType {
  id: string
  name: string
  billing_type: string
  price: number
  value: number
  application_id: string
}

interface Application {
  id: string
  name: string
}

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

const form = ref({
  application_id: '',
  card_type_id: '',
  count: 1,
})

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)
  }
}

async function fetchCardTypes() {
  try {
    const data = await api.get<{ card_types: CardType[] }>('/dev/card-types')
    cardTypes.value = Array.isArray(data?.card_types) ? data.card_types : []
  }
  catch (error) {
    console.error('获取卡类列表失败:', error)
  }
}

const filteredCardTypes = computed(() => {
  if (form.value.application_id) {
    return cardTypes.value.filter(
      ct => String(ct.application_id) === form.value.application_id,
    )
  }
  return []
})

const selectedCardType = computed(() => {
  if (form.value.card_type_id) {
    return cardTypes.value.find(ct => String(ct.id) === form.value.card_type_id)
  }
  return null
})

const totalCost = computed(() => {
  if (selectedCardType.value) {
    return selectedCardType.value.price * form.value.count
  }
  return 0
})

function onApplicationChange() {
  form.value.card_type_id = ''
}

async function handleGenerate() {
  if (!form.value.application_id) {
    toast.error(t('admin.cards.create.selectAppFirst'))
    return
  }
  if (!form.value.card_type_id) {
    toast.error(t('admin.cards.create.selectCardTypeFirst'))
    return
  }
  if (form.value.count < 1 || form.value.count > 1000) {
    toast.error(t('admin.cards.create.countRange'))
    return
  }

  saving.value = true
  try {
    await api.post('/dev/cards/batch', {
      application_id: Number(form.value.application_id),
      card_type_id: Number(form.value.card_type_id),
      count: form.value.count,
    })
    toast.success(t('admin.cards.create.generateSuccess', { count: form.value.count }))
    router.push('/admin/cards')
  }
  catch (error: any) {
    console.error('生成卡密失败:', error)
    toast.error(error.message || t('admin.cards.create.generateFailed'))
  }
  finally {
    saving.value = false
  }
}

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

<template>
  <BasicPage
    :title="t('admin.cards.create.title')"
    :description="t('admin.cards.create.description')"
    :breadcrumbs="[
      { title: t('admin.cards.title'), href: '/admin/cards' },
      { title: t('admin.cards.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.cards.create.config') }}
              </UiCardTitle>
              <UiCardDescription>{{ t('admin.cards.create.configDesc') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel for="application">
                  {{ t('admin.cards.create.application') }}
                </UiLabel>
                <UiSelect v-model="form.application_id" @update:model-value="onApplicationChange">
                  <UiSelectTrigger>
                    <UiSelectValue :placeholder="t('admin.cards.create.selectApplication')" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem v-for="app in applications" :key="app.id" :value="String(app.id)">
                      {{ app.name }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>

              <div class="space-y-2">
                <UiLabel for="cardType">
                  {{ t('admin.cards.create.cardType') }}
                </UiLabel>
                <UiSelect v-model="form.card_type_id" :disabled="!form.application_id">
                  <UiSelectTrigger>
                    <UiSelectValue :placeholder="t('admin.cards.create.selectCardType')" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem v-for="type in filteredCardTypes" :key="type.id" :value="String(type.id)">
                      {{ type.name }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
                <p v-if="form.application_id && filteredCardTypes.length === 0" class="text-xs text-muted-foreground">
                  {{ t('admin.cards.create.noCardType') }}
                </p>
              </div>

              <div class="space-y-2">
                <UiLabel for="count">
                  {{ t('admin.cards.create.count') }}
                </UiLabel>
                <div class="flex items-center gap-4">
                  <UiNumberField v-model="form.count" :min="1" :max="1000" class="flex-1 max-w-[200px]">
                    <UiNumberFieldContent>
                      <UiNumberFieldDecrement />
                      <UiNumberFieldInput />
                      <UiNumberFieldIncrement />
                    </UiNumberFieldContent>
                  </UiNumberField>
                  <div class="flex gap-2">
                    <UiButton variant="outline" size="sm" @click="form.count = 10">
                      10
                    </UiButton>
                    <UiButton variant="outline" size="sm" @click="form.count = 50">
                      50
                    </UiButton>
                    <UiButton variant="outline" size="sm" @click="form.count = 100">
                      100
                    </UiButton>
                    <UiButton variant="outline" size="sm" @click="form.count = 500">
                      500
                    </UiButton>
                  </div>
                </div>
                <p class="text-xs text-muted-foreground">
                  {{ t('admin.cards.create.maxCount') }}
                </p>
              </div>
            </UiCardContent>
          </UiCard>
        </div>

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Receipt class="size-5" />
                {{ t('admin.cards.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.cards.create.app') }}</span>
                  <span>{{ applications.find(a => String(a.id) === form.application_id)?.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.cards.create.type') }}</span>
                  <span>{{ selectedCardType?.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.cards.create.unitPrice') }}</span>
                  <span>¥{{ selectedCardType?.price?.toFixed(2) || '0.00' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.cards.create.quantity') }}</span>
                  <span>{{ form.count }} {{ t('admin.cards.create.units') }}</span>
                </div>
                <div class="border-t pt-3 mt-3">
                  <div class="flex justify-between items-center">
                    <span class="text-muted-foreground">{{ t('admin.cards.create.totalAmount') }}</span>
                    <span class="text-xl font-bold text-primary">¥{{ totalCost.toFixed(2) }}</span>
                  </div>
                </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.application_id || !form.card_type_id"
                  @click="handleGenerate"
                >
                  <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
                  <Sparkles v-else class="mr-2 h-4 w-4" />
                  {{ t('admin.cards.create.generateNow') }}
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  {{ t('admin.cards.create.cancel') }}
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
