<script setup lang="ts">
// @iconify/vue 保留用于品牌图标（支付宝、微信、Stripe、PayPal、USDT），这些图标在 lucide 中不存在
import { Icon } from '@iconify/vue'
import { CreditCard, Eye, Loader2, Save, Wallet } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

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

const route = useRoute()
const router = useRouter()

const loading = ref(true)
const saving = ref(false)

const formData = ref({
  name: '',
  type: 'alipay' as 'alipay' | 'wechat' | 'stripe' | 'paypal' | 'bepusdt' | 'epay' | 'other',
  icon: '',
  config: '',
  sort: 0,
  status: 'active' as 'active' | 'inactive',
  remark: '',
})

const typeOptions = [
  { value: 'alipay', label: '支付宝', icon: 'ri:alipay-fill', color: 'text-blue-500', isBrand: true },
  { value: 'wechat', label: '微信支付', icon: 'ri:wechat-pay-fill', color: 'text-green-500', isBrand: true },
  { value: 'stripe', label: 'Stripe', icon: 'logos:stripe', color: '', isBrand: true },
  { value: 'paypal', label: 'PayPal', icon: 'logos:paypal', color: '', isBrand: true },
  { value: 'bepusdt', label: 'BEPUSDT', icon: 'cryptocurrency:usdt', color: 'text-green-500', isBrand: true },
  { value: 'epay', label: '易支付', iconComponent: Wallet, color: 'text-orange-500' },
  { value: 'other', label: '其他', iconComponent: CreditCard, color: 'text-gray-500' },
]

const selectedType = computed(() => {
  return typeOptions.find(t => t.value === formData.value.type)
})

async function fetchPaymentChannel() {
  loading.value = true
  try {
    const data = await api.get(`/dev/payment-channels/${route.params.id}`)
    if (data) {
      formData.value = {
        name: data.name,
        type: data.type,
        icon: data.icon || '',
        config: data.config || '',
        sort: data.sort || 0,
        status: data.status,
        remark: data.remark || '',
      }
    }
  }
  catch (error: any) {
    console.error('加载支付渠道失败:', error)
    toast.error(error.message || '加载失败')
    router.push('/admin/payment-channels')
  }
  finally {
    loading.value = false
  }
}

async function handleSubmit() {
  if (!formData.value.name) {
    toast.error('请输入渠道名称')
    return
  }

  saving.value = true
  try {
    await api.put(`/dev/payment-channels/${route.params.id}`, formData.value)
    toast.success('更新成功')
    router.push('/admin/payment-channels')
  }
  catch (error: any) {
    console.error('更新支付渠道失败:', error)
    toast.error(error.message || '更新失败')
  }
  finally {
    saving.value = false
  }
}

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

<template>
  <BasicPage
    title="编辑支付渠道"
    description="修改支付渠道配置"
    :breadcrumbs="[
      { title: '支付渠道', href: '/admin/payment-channels' },
      { title: '编辑渠道' },
    ]"
    sticky
  >
    <div v-if="loading" class="flex items-center justify-center py-8">
      <div class="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
    </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">
                <CreditCard class="size-5" />
                渠道配置
              </UiCardTitle>
              <UiCardDescription>修改支付渠道的基本信息</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="grid gap-4 md:grid-cols-2">
                <div class="space-y-2">
                  <UiLabel for="name">
                    渠道名称 <span class="text-destructive">*</span>
                  </UiLabel>
                  <UiInput
                    id="name"
                    v-model="formData.name"
                    placeholder="输入渠道名称"
                    :disabled="saving"
                  />
                </div>

                <div class="space-y-2">
                  <UiLabel>渠道类型 <span class="text-destructive">*</span></UiLabel>
                  <UiSelect v-model="formData.type" :disabled="saving">
                    <UiSelectTrigger>
                      <UiSelectValue placeholder="选择渠道类型" />
                    </UiSelectTrigger>
                    <UiSelectContent>
                      <UiSelectItem v-for="type in typeOptions" :key="type.value" :value="type.value">
                        <div class="flex items-center gap-2">
                          <Icon v-if="type.isBrand" :icon="type.icon" :class="['h-4 w-4', type.color]" />
                          <component v-else :is="type.iconComponent" :class="['h-4 w-4', type.color]" />
                          {{ type.label }}
                        </div>
                      </UiSelectItem>
                    </UiSelectContent>
                  </UiSelect>
                </div>

                <div class="space-y-2">
                  <UiLabel for="icon">图标URL</UiLabel>
                  <UiInput
                    id="icon"
                    v-model="formData.icon"
                    placeholder="输入图标URL（可选）"
                    :disabled="saving"
                  />
                </div>

                <div class="space-y-2">
                  <UiLabel for="sort">排序</UiLabel>
                  <UiInput
                    id="sort"
                    v-model.number="formData.sort"
                    type="number"
                    placeholder="0"
                    :disabled="saving"
                  />
                </div>
              </div>

              <div class="space-y-2">
                <UiLabel for="config">配置信息</UiLabel>
                <textarea
                  id="config"
                  v-model="formData.config"
                  class="flex min-h-[120px] 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="JSON格式的配置信息（如AppID、密钥等）"
                  :disabled="saving"
                />
              </div>

              <div class="space-y-2">
                <UiLabel for="remark">备注</UiLabel>
                <UiInput
                  id="remark"
                  v-model="formData.remark"
                  placeholder="备注信息（可选）"
                  :disabled="saving"
                />
              </div>

              <div class="flex items-center justify-between rounded-lg border p-4">
                <div class="space-y-0.5">
                  <UiLabel class="text-base">
                    启用状态
                  </UiLabel>
                  <p class="text-sm text-muted-foreground">
                    启用后该支付渠道将对用户可见
                  </p>
                </div>
                <UiSwitch
                  :checked="formData.status === 'active'"
                  :disabled="saving"
                  @update:checked="formData.status = $event ? 'active' : 'inactive'"
                />
              </div>
            </UiCardContent>
          </UiCard>
        </div>

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Eye class="size-5" />
                预览
              </UiCardTitle>
            </UiCardHeader>
            <UiCardContent class="space-y-4">
              <div class="space-y-3">
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">渠道名称</span>
                  <span class="truncate max-w-[120px]">{{ formData.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">渠道类型</span>
                  <div class="flex items-center gap-1.5">
                    <Icon v-if="selectedType?.isBrand" :icon="selectedType?.icon" :class="['h-4 w-4', selectedType?.color]" />
                    <component v-else :is="selectedType?.iconComponent || CreditCard" :class="['h-4 w-4', selectedType?.color]" />
                    <span>{{ selectedType?.label || '-' }}</span>
                  </div>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">排序</span>
                  <span>{{ formData.sort }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">状态</span>
                  <span>{{ formData.status === 'active' ? '启用' : '禁用' }}</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.name"
                  @click="handleSubmit"
                >
                  <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
                  <Save v-else class="mr-2 h-4 w-4" />
                  保存修改
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  取消
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
