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

import { BasicPage } from '@/components/global-layout'
import api from '@/services/api'

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

interface Application {
  id: string
  name: string
  billing_type: string
}

const cardTypeId = computed(() => route.params.id as string)
const loading = ref(true)
const saving = ref(false)
const applications = ref<Application[]>([])

const form = ref({
  name: '',
  description: '',
  application_id: '',
  price: 0,
  recharge_type: 'balance' as 'balance' | 'subscription',
  value: 1,
  value_unit: 'day' as 'day' | 'month' | 'year',
  is_permanent: false,
})

async function fetchCardType() {
  loading.value = true
  try {
    const data = await api.get<any>(`/dev/card-types/${cardTypeId.value}`)
    const ct = data?.card_type || data
    if (ct) {
      form.value.name = ct.name || ''
      form.value.description = ct.description || ''
      form.value.application_id = String(ct.application_id || '')
      form.value.price = ct.price || 0
      form.value.recharge_type = ct.recharge_type || 'balance'
      form.value.is_permanent = ct.value === -1
      form.value.value = ct.value === -1 ? 1 : ct.value
      form.value.value_unit = ct.value_unit || 'day'
    }
  }
  catch (error) {
    console.error('获取卡密类型失败:', error)
    toast.error(t('admin.cardTypes.editFailed'))
  }
  finally {
    loading.value = false
  }
}

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

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

watch(selectedApplication, (app) => {
  if (app) {
    if (app.billing_type === 'subscription') {
      form.value.recharge_type = 'subscription'
    }
    else if (app.billing_type === 'time' || app.billing_type === 'count') {
      form.value.recharge_type = 'balance'
    }
  }
})

const displayValue = computed(() => {
  if (form.value.is_permanent) {
    return t('admin.cardTypes.units.permanent')
  }
  if (form.value.recharge_type === 'subscription') {
    const unitMap: Record<string, string> = {
      minute: t('admin.cardTypes.units.minute'),
      hour: t('admin.cardTypes.units.hour'),
      day: t('admin.cardTypes.units.day'),
      month: t('admin.cardTypes.units.month'),
      year: t('admin.cardTypes.units.year'),
    }
    return `${form.value.value} ${unitMap[form.value.value_unit]}`
  }
  return `${form.value.value}`
})

async function handleSave() {
  if (!form.value.name) {
    toast.error(t('admin.cardTypes.create.nameRequired'))
    return
  }

  if (!form.value.application_id) {
    toast.error(t('admin.cardTypes.create.applicationRequired'))
    return
  }

  if (!form.value.is_permanent && form.value.value <= 0) {
    toast.error(t('admin.cardTypes.create.valueRequired'))
    return
  }

  saving.value = true
  try {
    await api.put(`/dev/card-types/${cardTypeId.value}`, {
      application_id: Number(form.value.application_id),
      name: form.value.name,
      description: form.value.description,
      recharge_type: form.value.recharge_type,
      value: form.value.is_permanent ? -1 : form.value.value,
      value_unit: form.value.recharge_type === 'subscription' ? form.value.value_unit : '',
      price: form.value.price,
    })
    toast.success(t('admin.cardTypes.editSuccess'))
    router.push('/admin/card-types')
  }
  catch (error: any) {
    console.error('更新卡密类型失败:', error)
    toast.error(error.message || t('admin.cardTypes.editFailed'))
  }
  finally {
    saving.value = false
  }
}

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

<template>
  <BasicPage
    :title="t('admin.cardTypes.edit')"
    :description="t('admin.cardTypes.create.description')"
    :breadcrumbs="[
      { title: t('admin.cardTypes.title'), href: '/admin/card-types' },
      { title: t('admin.cardTypes.edit') },
    ]"
    sticky
  >
    <div v-if="loading" class="flex items-center justify-center py-12">
      <Loader2 class="size-8 animate-spin text-muted-foreground" />
    </div>

    <div v-else 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">
                <Info class="size-5" />
                {{ t('admin.cardTypes.create.basicInfo') }}
              </UiCardTitle>
              <UiCardDescription>{{ t('admin.cardTypes.create.basicInfoDesc') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel for="name">
                  {{ t('admin.cardTypes.create.name') }} *
                </UiLabel>
                <UiInput id="name" v-model="form.name" :placeholder="t('admin.cardTypes.create.namePlaceholder')" />
              </div>

              <div class="space-y-2">
                <UiLabel for="description">
                  {{ t('admin.cardTypes.create.description') }}
                </UiLabel>
                <UiTextarea id="description" v-model="form.description" :placeholder="t('admin.cardTypes.create.descriptionPlaceholder')" rows="3" />
              </div>

              <div class="space-y-2">
                <UiLabel for="application">
                  {{ t('admin.cardTypes.create.application') }} *
                </UiLabel>
                <UiSelect v-model="form.application_id">
                  <UiSelectTrigger>
                    <UiSelectValue :placeholder="t('admin.cardTypes.create.selectApplication')" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem v-for="app in applications" :key="app.id" :value="String(app.id)">
                      {{ app.name }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>
            </UiCardContent>
          </UiCard>

          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <CreditCard class="size-5" />
                {{ t('admin.cardTypes.create.rechargeConfig') }}
              </UiCardTitle>
              <UiCardDescription>{{ t('admin.cardTypes.create.rechargeConfigDesc') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel>{{ t('admin.cardTypes.create.rechargeType') }}</UiLabel>
                <UiRadioGroup v-model="form.recharge_type" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div
                    class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                    :class="form.recharge_type === 'balance' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                    @click="form.recharge_type = 'balance'"
                  >
                    <UiRadioGroupItem value="balance" class="mt-0.5" />
                    <div>
                      <p class="font-medium">
                        {{ t('admin.cardTypes.create.balanceRecharge') }}
                      </p>
                      <p class="text-sm text-muted-foreground">
                        {{ t('admin.cardTypes.create.balanceRechargeDesc') }}
                      </p>
                    </div>
                  </div>

                  <div
                    class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                    :class="form.recharge_type === 'subscription' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                    @click="form.recharge_type = 'subscription'"
                  >
                    <UiRadioGroupItem value="subscription" class="mt-0.5" />
                    <div>
                      <p class="font-medium">
                        {{ t('admin.cardTypes.create.subscriptionRecharge') }}
                      </p>
                      <p class="text-sm text-muted-foreground">
                        {{ t('admin.cardTypes.create.subscriptionRechargeDesc') }}
                      </p>
                    </div>
                  </div>
                </UiRadioGroup>
              </div>

              <div class="space-y-2">
                <UiLabel for="price">
                  {{ t('admin.cardTypes.create.price') }}
                </UiLabel>
                <div class="flex items-center gap-2">
                  <UiNumberField v-model="form.price" :min="0" :step="0.01" class="max-w-[200px]">
                    <UiNumberFieldContent>
                      <UiNumberFieldDecrement />
                      <UiNumberFieldInput />
                      <UiNumberFieldIncrement />
                    </UiNumberFieldContent>
                  </UiNumberField>
                  <span class="text-sm text-muted-foreground">{{ t('admin.cardTypes.create.priceUnit') }}</span>
                </div>
              </div>

              <div class="flex items-center justify-between pt-4 border-t">
                <div>
                  <p class="font-medium">
                    {{ t('admin.cardTypes.create.permanentLabel') }}
                  </p>
                  <p class="text-sm text-muted-foreground">
                    {{ t('admin.cardTypes.create.permanentLabelDesc') }}
                  </p>
                </div>
                <UiSwitch v-model="form.is_permanent" />
              </div>

              <div v-if="!form.is_permanent" class="space-y-4 pt-4 border-t">
                <div v-if="form.recharge_type === 'balance'" class="space-y-2">
                  <UiLabel>{{ t('admin.cardTypes.create.rechargeAmount') }}</UiLabel>
                  <UiNumberField v-model="form.value" :min="0.01" :step="0.01" class="max-w-[200px]">
                    <UiNumberFieldContent>
                      <UiNumberFieldDecrement />
                      <UiNumberFieldInput />
                      <UiNumberFieldIncrement />
                    </UiNumberFieldContent>
                  </UiNumberField>
                  <p class="text-xs text-muted-foreground">
                    {{ t('admin.cardTypes.create.rechargeAmountDesc') }}
                  </p>
                </div>

                <div v-if="form.recharge_type === 'subscription'" class="space-y-4">
                  <div class="grid grid-cols-2 gap-4">
                    <div class="space-y-2">
                      <UiLabel>{{ t('admin.cardTypes.create.rechargeDuration') }}</UiLabel>
                      <UiNumberField v-model="form.value" :min="1" :step="1">
                        <UiNumberFieldContent>
                          <UiNumberFieldDecrement />
                          <UiNumberFieldInput />
                          <UiNumberFieldIncrement />
                        </UiNumberFieldContent>
                      </UiNumberField>
                    </div>

                    <div class="space-y-2">
                      <UiLabel>{{ t('admin.cardTypes.create.durationUnit') }}</UiLabel>
                      <UiSelect v-model="form.value_unit">
                        <UiSelectTrigger>
                          <UiSelectValue />
                        </UiSelectTrigger>
                        <UiSelectContent>
                          <UiSelectItem value="minute">
                            {{ t('admin.cardTypes.units.minute') }}
                          </UiSelectItem>
                          <UiSelectItem value="hour">
                            {{ t('admin.cardTypes.units.hour') }}
                          </UiSelectItem>
                          <UiSelectItem value="day">
                            {{ t('admin.cardTypes.units.day') }}
                          </UiSelectItem>
                          <UiSelectItem value="month">
                            {{ t('admin.cardTypes.units.month') }}
                          </UiSelectItem>
                          <UiSelectItem value="year">
                            {{ t('admin.cardTypes.units.year') }}
                          </UiSelectItem>
                        </UiSelectContent>
                      </UiSelect>
                    </div>
                  </div>
                </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.cardTypes.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.cardTypes.create.previewName') }}</span>
                  <span>{{ form.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.cardTypes.create.previewApplication') }}</span>
                  <span>{{ selectedApplication?.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.cardTypes.create.rechargeType') }}</span>
                  <span>{{ form.recharge_type === 'balance' ? t('admin.cardTypes.create.balanceRecharge') : t('admin.cardTypes.create.subscriptionRecharge') }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.cardTypes.create.previewPrice') }}</span>
                  <span>¥{{ form.price.toFixed(2) }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.cardTypes.create.previewValue') }}</span>
                  <span>{{ displayValue }}</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"
                  @click="handleSave"
                >
                  <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.cardTypes.create.saveBtn') }}
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  {{ t('admin.cardTypes.create.cancel') }}
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
