<script setup lang="ts">
import { CreditCard, Eye, Loader2, UserPlus } 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 api from '@/services/api'

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

interface Application {
  id: string
  name: string
}

interface CardType {
  id: number
  name: string
  recharge_type: string
  value: number
  value_unit: string
  price: number
  description: string
}

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

const form = ref({
  username: '',
  email: '',
  password: '',
  application_id: '',
  card_type_id: 'none',
  card_quantity: 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(applicationId: string) {
  if (!applicationId) {
    cardTypes.value = []
    return
  }
  try {
    const data = await api.get<{ card_types: CardType[] }>(`/dev/card-types?application_id=${applicationId}`)
    cardTypes.value = Array.isArray(data?.card_types) ? data.card_types : []
  }
  catch (error) {
    console.error('获取卡密类型失败:', error)
    cardTypes.value = []
  }
}

watch(() => form.value.application_id, (newVal) => {
  form.value.card_type_id = 'none'
  fetchCardTypes(newVal)
})

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

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

function formatCardTypeValue(ct: CardType) {
  if (ct.value === -1)
    return t('admin.users.create.permanent')
  if (ct.recharge_type === 'subscription') {
    const unitMap: Record<string, string> = {
      minute: t('admin.users.create.minutes'),
      hour: t('admin.users.create.hours'),
      day: t('admin.users.create.days'),
      month: t('admin.users.create.months'),
      year: t('admin.users.create.years'),
    }
    return `${ct.value} ${unitMap[ct.value_unit] || ct.value_unit}`
  }
  return `${ct.value} ${t('admin.users.create.points')}`
}

const isFormValid = computed(() => {
  return form.value.username && form.value.password && form.value.application_id
})

async function handleSave() {
  if (!form.value.username) {
    toast.error(t('admin.users.create.usernameRequired'))
    return
  }
  if (!form.value.password) {
    toast.error(t('admin.users.create.passwordRequired'))
    return
  }
  if (!form.value.application_id) {
    toast.error(t('admin.users.create.applicationRequired'))
    return
  }

  saving.value = true
  try {
    const payload: any = {
      username: form.value.username,
      email: form.value.email,
      password: form.value.password,
      application_id: Number(form.value.application_id),
    }
    if (form.value.card_type_id && form.value.card_type_id !== 'none') {
      payload.card_type_id = Number(form.value.card_type_id)
      payload.card_quantity = form.value.card_quantity || 1
    }
    await api.post('/dev/app-users', payload)
    toast.success(t('admin.users.create.success'))
    router.push('/admin/users')
  }
  catch (error: any) {
    console.error('创建用户失败:', error)
    toast.error(error.message || t('admin.users.create.failed'))
  }
  finally {
    saving.value = false
  }
}

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

<template>
  <BasicPage
    :title="t('admin.users.create.title')"
    :description="t('admin.users.create.description')"
    :breadcrumbs="[
      { title: t('admin.users.title'), href: '/admin/users' },
      { title: t('admin.users.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">
                <UserPlus class="size-5" />
                {{ t('admin.users.create.basicInfo') }}
              </UiCardTitle>
              <UiCardDescription>{{ t('admin.users.create.basicInfoDesc') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel for="application">
                  {{ t('admin.users.create.application') }}
                </UiLabel>
                <UiSelect v-model="form.application_id">
                  <UiSelectTrigger>
                    <UiSelectValue :placeholder="t('admin.users.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="username">
                  {{ t('admin.users.create.username') }}
                </UiLabel>
                <UiInput id="username" v-model="form.username" :placeholder="t('admin.users.create.usernamePlaceholder')" />
              </div>

              <div class="space-y-2">
                <UiLabel for="password">
                  {{ t('admin.users.create.password') }}
                </UiLabel>
                <UiInput id="password" v-model="form.password" type="password" :placeholder="t('admin.users.create.passwordPlaceholder')" />
              </div>

              <div class="space-y-2">
                <UiLabel for="email">
                  {{ t('admin.users.create.email') }}
                </UiLabel>
                <UiInput id="email" v-model="form.email" type="email" :placeholder="t('admin.users.create.emailPlaceholder')" />
              </div>
            </UiCardContent>
          </UiCard>

          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <CreditCard class="size-5" />
                {{ t('admin.users.create.rechargeCard') }}
              </UiCardTitle>
              <UiCardDescription>{{ t('admin.users.create.rechargeCardDesc') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel for="card_type">
                  {{ t('admin.users.create.cardType') }}
                </UiLabel>
                <UiSelect v-model="form.card_type_id">
                  <UiSelectTrigger>
                    <UiSelectValue :placeholder="cardTypes.length > 0 ? t('admin.users.create.selectCardType') : t('admin.users.create.selectApplicationFirst')" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem value="none">
                      {{ t('admin.users.create.noRecharge') }}
                    </UiSelectItem>
                    <UiSelectItem v-for="ct in cardTypes" :key="ct.id" :value="String(ct.id)">
                      {{ ct.name }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>

              <div v-if="selectedCardType" class="space-y-2">
                <UiLabel for="card_quantity">
                  {{ t('admin.users.create.cardQuantity') }}
                </UiLabel>
                <UiNumberField v-model="form.card_quantity" :min="1" :max="100" class="max-w-[200px]">
                  <UiNumberFieldContent>
                    <UiNumberFieldDecrement />
                    <UiNumberFieldInput />
                    <UiNumberFieldIncrement />
                  </UiNumberFieldContent>
                </UiNumberField>
              </div>

              <div v-if="selectedCardType" class="rounded-lg border bg-muted/50 p-3 space-y-2">
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.users.create.cardType') }}</span>
                  <span>{{ selectedCardType.name }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.users.create.cardValue') }}</span>
                  <span>{{ formatCardTypeValue(selectedCardType) }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.users.create.cardQuantity') }}</span>
                  <span>{{ form.card_quantity }}</span>
                </div>
              </div>
            </UiCardContent>
          </UiCard>
        </div>

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Eye class="size-5" />
                {{ t('admin.users.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.users.create.app') }}</span>
                  <span>{{ selectedApplication?.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.users.create.usernameLabel') }}</span>
                  <span>{{ form.username || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.users.create.emailLabel') }}</span>
                  <span>{{ form.email || '-' }}</span>
                </div>
                <div v-if="selectedCardType" class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.users.create.rechargeCard') }}</span>
                  <span class="text-primary">{{ selectedCardType.name }} x{{ form.card_quantity }}</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 || !isFormValid"
                  @click="handleSave"
                >
                  <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
                  <UserPlus v-else class="mr-2 h-4 w-4" />
                  {{ t('admin.users.create.submit') }}
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  {{ t('admin.users.create.cancel') }}
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
