<script setup lang="ts">
import { Loader2 } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import api from '@/services/api'

const { t } = useI18n()
const route = useRoute()
const router = useRouter()

const loading = ref(false)
const apps = ref<any[]>([])
const cardTypes = ref<any[]>([])

const form = ref({
  app_id: route.query.app_id || '',
  card_type_id: route.query.card_type_id || '',
  quantity: 1,
})

const _selectedApp = computed(() => {
  return apps.value.find(a => a.id === Number(form.value.app_id))
})

const availableCardTypes = computed(() => {
  return cardTypes.value.filter(ct => ct.app_id === Number(form.value.app_id))
})

const totalPrice = computed(() => {
  const ct = cardTypes.value.find(c => c.id === Number(form.value.card_type_id))
  return ct ? ct.price * form.value.quantity : 0
})

onMounted(async () => {
  try {
    const data = await api.get<any[]>('/agent/apps')
    apps.value = data || []

    if (apps.value.length > 0) {
      const typesData = await api.get<any[]>('/agent/card-types')
      cardTypes.value = typesData || []
    }
  }
  catch (error) {
    console.error('Load data failed:', error)
  }
})

async function handleGenerate() {
  if (!form.value.app_id) {
    toast.error(t('agent.cards.create.selectApp'))
    return
  }
  if (!form.value.card_type_id) {
    toast.error(t('agent.cards.create.selectCardType'))
    return
  }
  if (form.value.quantity < 1 || form.value.quantity > 100) {
    toast.error(t('agent.cards.create.quantityRange'))
    return
  }

  loading.value = true
  try {
    const data = await api.post<{ codes: string[], cards: any[] }>('/agent/cards/generate', {
      app_id: Number(form.value.app_id),
      card_type_id: Number(form.value.card_type_id),
      quantity: form.value.quantity,
    })

    toast.success(t('agent.cards.create.generateSuccess', { count: data.codes.length }))

    const codesText = data.codes.join('\n')
    await navigator.clipboard.writeText(codesText)
    toast.success(t('agent.cards.create.copiedToClipboard'))

    router.push('/agent/cards')
  }
  catch (error: any) {
    console.error('Generate cards failed:', error)
    toast.error(error.message || t('agent.cards.create.generateFailed'))
  }
  finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="space-y-6">
    <div>
      <h1 class="text-2xl font-bold">
        {{ t('agent.cards.create.title') }}
      </h1>
      <p class="text-muted-foreground">
        {{ t('agent.cards.create.description') }}
      </p>
    </div>

    <UiCard class="max-w-xl">
      <UiCardHeader>
        <UiCardTitle>{{ t('agent.cards.create.generateSettings') }}</UiCardTitle>
        <UiCardDescription>
          {{ t('agent.cards.create.settingsDesc') }}
        </UiCardDescription>
      </UiCardHeader>
      <UiCardContent class="space-y-6">
        <div class="space-y-2">
          <UiLabel>{{ t('agent.cards.create.selectAppLabel') }}</UiLabel>
          <UiSelect v-model="form.app_id">
            <UiSelectTrigger>
              <UiSelectValue :placeholder="t('agent.cards.create.selectAppPlaceholder')" />
            </UiSelectTrigger>
            <UiSelectContent>
              <UiSelectItem v-for="app in apps" :key="app.id" :value="String(app.id)">
                {{ app.name }}
              </UiSelectItem>
            </UiSelectContent>
          </UiSelect>
        </div>

        <div v-if="form.app_id" class="space-y-2">
          <UiLabel>{{ t('agent.cards.create.selectCardTypeLabel') }}</UiLabel>
          <UiSelect v-model="form.card_type_id">
            <UiSelectTrigger>
              <UiSelectValue :placeholder="t('agent.cards.create.selectCardTypePlaceholder')" />
            </UiSelectTrigger>
            <UiSelectContent>
              <UiSelectItem v-for="ct in availableCardTypes" :key="ct.id" :value="String(ct.id)">
                {{ ct.name }} - {{ ct.duration_days }}{{ t('agent.apps.detail.days') }} - ¥{{ ct.price }}
              </UiSelectItem>
            </UiSelectContent>
          </UiSelect>
        </div>

        <div class="space-y-2">
          <UiLabel>{{ t('agent.cards.create.quantity') }}</UiLabel>
          <UiInput
            v-model.number="form.quantity"
            type="number"
            :min="1"
            :max="100"
            :placeholder="t('agent.cards.create.quantityPlaceholder')"
          />
          <p class="text-xs text-muted-foreground">
            {{ t('agent.cards.create.quantityHint') }}
          </p>
        </div>

        <div v-if="totalPrice > 0" class="p-4 rounded-lg bg-muted/50">
          <div class="flex items-center justify-between">
            <span class="text-muted-foreground">{{ t('agent.cards.create.estimatedCost') }}</span>
            <span class="text-xl font-bold">¥{{ totalPrice.toFixed(2) }}</span>
          </div>
        </div>

        <div class="flex gap-3">
          <UiButton variant="outline" as-child>
            <router-link to="/agent/cards">
              {{ t('agent.cards.create.cancel') }}
            </router-link>
          </UiButton>
          <UiButton
            :disabled="loading || !form.app_id || !form.card_type_id"
            @click="handleGenerate"
          >
            <Loader2 v-if="loading" class="mr-2 h-4 w-4 animate-spin" />
            {{ loading ? t('agent.cards.create.generating') : t('agent.cards.create.generateBtn') }}
          </UiButton>
        </div>
      </UiCardContent>
    </UiCard>
  </div>
</template>
