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

import { BasicPage } from '@/components/global-layout'
import { NumberField, NumberFieldContent, NumberFieldDecrement, NumberFieldIncrement, NumberFieldInput } from '@/components/ui/number-field'
import api from '@/services/api'

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

interface Agent {
  id: number
  username: string
}

interface Application {
  id: number
  name: string
}

interface CardType {
  id: number
  name: string
  billing_type: string
  price: number
}

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

const formData = ref({
  agent_id: '',
  application_id: '',
  card_type_id: '',
  price: 0,
  remark: '',
})

const selectedAgent = computed(() => {
  if (formData.value.agent_id) {
    return agents.value.find(a => String(a.id) === formData.value.agent_id)
  }
  return null
})

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

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

async function fetchAgents() {
  try {
    const data = await api.get<{ agents?: Agent[] }>('/dev/agents')
    agents.value = data?.agents || []
  }
  catch (error) {
    console.error('获取代理列表失败:', error)
  }
}

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

async function fetchCardTypes(appId: string) {
  if (!appId) {
    cardTypes.value = []
    formData.value.card_type_id = ''
    formData.value.price = 0
    return
  }
  try {
    const data = await api.get<{ card_types: CardType[] }>(`/dev/card-types?application_id=${appId}`)
    cardTypes.value = data?.card_types || []
    formData.value.card_type_id = ''
    formData.value.price = 0
  }
  catch {
    cardTypes.value = []
    formData.value.card_type_id = ''
    formData.value.price = 0
  }
}

function handleAppChange(value: string | number | bigint | Record<string, any> | null | undefined) {
  fetchCardTypes(String(value || ''))
}

watch(selectedCardType, (ct) => {
  if (ct) {
    formData.value.price = ct.price
  }
})

async function handleSubmit() {
  if (!formData.value.agent_id) {
    toast.error(t('admin.agentApps.createForm.selectAgentRequired'))
    return
  }

  if (!formData.value.application_id) {
    toast.error(t('admin.agentApps.createForm.selectAppRequired'))
    return
  }

  if (!formData.value.card_type_id) {
    toast.error(t('admin.agentApps.createForm.selectCardRequired'))
    return
  }

  saving.value = true
  try {
    await api.post('/dev/agent-apps/authorize', {
      agent_id: Number(formData.value.agent_id),
      application_id: Number(formData.value.application_id),
      discount: 1.0,
      card_types: [{
        card_type_id: Number(formData.value.card_type_id),
        can_generate: true,
        price: Number(formData.value.price),
      }],
    })
    toast.success(t('admin.agentApps.createForm.createSuccess'))
    router.push('/admin/agent-apps')
  }
  catch (error: any) {
    toast.error(error.message || t('admin.agentApps.createForm.createFailed'))
  }
  finally {
    saving.value = false
  }
}

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

<template>
  <BasicPage
    :title="t('admin.agentApps.createForm.title')"
    :description="t('admin.agentApps.createForm.description')"
    :breadcrumbs="[
      { title: t('nav.agentApps'), href: '/admin/agent-apps' },
      { title: t('admin.agentApps.createForm.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">
                <KeyRound class="size-5" />
                {{ t('admin.agentApps.createForm.authConfig') }}
              </UiCardTitle>
              <UiCardDescription>{{ t('admin.agentApps.createForm.authConfigDesc') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel>{{ t('admin.agentApps.createForm.selectAgent') }} <span class="text-destructive">*</span></UiLabel>
                <UiSelect v-model="formData.agent_id" :disabled="saving || loading">
                  <UiSelectTrigger>
                    <UiSelectValue :placeholder="t('admin.agentApps.createForm.selectAgentPlaceholder')" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem
                      v-for="agent in agents"
                      :key="agent.id"
                      :value="String(agent.id)"
                    >
                      {{ agent.username }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>

              <div class="space-y-2">
                <UiLabel>{{ t('admin.agentApps.createForm.selectApp') }} <span class="text-destructive">*</span></UiLabel>
                <UiSelect v-model="formData.application_id" :disabled="saving || loading" @update:model-value="handleAppChange">
                  <UiSelectTrigger>
                    <UiSelectValue :placeholder="t('admin.agentApps.createForm.selectAppPlaceholder')" />
                  </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>{{ t('admin.agentApps.createForm.selectCardType') }} <span class="text-destructive">*</span></UiLabel>
                <UiSelect v-model="formData.card_type_id" :disabled="!formData.application_id || saving">
                  <UiSelectTrigger>
                    <UiSelectValue :placeholder="t('admin.agentApps.createForm.selectCardTypePlaceholder')" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem v-for="ct in cardTypes" :key="ct.id" :value="String(ct.id)">
                      {{ ct.name }}<template v-if="ct.billing_type"> ({{ ct.billing_type }})</template>
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>

              <div class="space-y-2">
                <UiLabel>{{ t('admin.agentApps.createForm.price') }} <span class="text-destructive">*</span></UiLabel>
                <div class="flex items-center gap-2">
                  <NumberField
                    v-model="formData.price"
                    :min="0"
                    :step="0.01"
                    :disabled="saving"
                    class="w-32"
                  >
                    <NumberFieldContent>
                      <NumberFieldDecrement />
                      <NumberFieldInput />
                      <NumberFieldIncrement />
                    </NumberFieldContent>
                  </NumberField>
                  <span class="text-sm text-muted-foreground">¥</span>
                </div>
              </div>

              <div class="space-y-2">
                <UiLabel for="remark">{{ t('admin.agentApps.createForm.remark') }}</UiLabel>
                <textarea
                  id="remark"
                  v-model="formData.remark"
                  class="flex min-h-[80px] 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"
                  :placeholder="t('admin.agentApps.createForm.remarkPlaceholder')"
                  :disabled="saving"
                  rows="2"
                />
              </div>
            </UiCardContent>
          </UiCard>
        </div>

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Eye class="size-5" />
                {{ t('admin.agentApps.createForm.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.agentApps.createForm.previewAgent') }}</span>
                  <span>{{ selectedAgent?.username || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.agentApps.createForm.previewApp') }}</span>
                  <span>{{ selectedApplication?.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.agentApps.createForm.previewCardType') }}</span>
                  <span>{{ selectedCardType?.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.agentApps.createForm.previewPrice') }}</span>
                  <span>¥{{ formData.price || 0 }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.agentApps.createForm.previewRemark') }}</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.agent_id || !formData.application_id || !formData.card_type_id"
                  @click="handleSubmit"
                >
                  <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
                  <Rocket v-else class="mr-2 h-4 w-4" />
                  {{ t('admin.agentApps.createForm.confirmAuth') }}
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  {{ t('common.cancel') }}
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>