<script setup lang="ts">
import { ArrowLeft, Check, CheckCheck, Eye, Loader2, X } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import type { AgentApp, CardTypeAuth } from '@/pages/admin/agent-apps/data/schema'

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 agentApp = ref<AgentApp | null>(null)

const form = ref({
  status: 'active',
  discount: 1.0,
  card_types: [] as Array<{
    card_type_id: number
    name: string
    billing_type: string
    origin_price: number
    price: number
    can_generate: boolean
  }>,
})

const agentAppId = computed(() => route.params.id as string)

function getBillingTypeText(type: string) {
  const map: Record<string, string> = {
    subscription: '订阅',
    time: '计时',
    point: '点卡',
  }
  return map[type] || type
}

async function fetchAgentApp() {
  loading.value = true
  try {
    const [agentAppRes, cardTypesRes] = await Promise.all([
      api.get<{ agent_app: AgentApp }>(`/dev/agent-apps/${agentAppId.value}`),
      api.get<{ card_types: Array<{ id: number, name: string, billing_type: string, price: number }> }>('/dev/card-types'),
    ])

    if (agentAppRes?.agent_app) {
      agentApp.value = agentAppRes.agent_app
      form.value.status = agentAppRes.agent_app.status || 'active'
      form.value.discount = agentAppRes.agent_app.discount || 1.0

      const existingPerms = agentAppRes.agent_app.card_types || []
      const allCardTypes = cardTypesRes?.card_types || []

      form.value.card_types = allCardTypes.map((ct) => {
        const existing = existingPerms.find((p: CardTypeAuth) => (p.card_type_id || p.id) === ct.id)
        return {
          card_type_id: ct.id,
          name: ct.name,
          billing_type: ct.billing_type,
          origin_price: ct.price,
          price: existing?.price || ct.price,
          can_generate: existing ? existing.can_generate : false,
        }
      })
    }
    else {
      toast.error('获取授权信息失败')
      router.push('/admin/agent-apps')
    }
  }
  catch (error) {
    console.error('获取授权信息失败:', error)
    toast.error('获取授权信息失败')
    router.push('/admin/agent-apps')
  }
  finally {
    loading.value = false
  }
}

function selectAll() {
  form.value.card_types.forEach(ct => ct.can_generate = true)
}

function clearAll() {
  form.value.card_types.forEach(ct => ct.can_generate = false)
}

async function handleSubmit() {
  if (form.value.discount < 0 || form.value.discount > 1) {
    toast.error('折扣必须在0-1之间')
    return
  }

  saving.value = true
  try {
    await api.put(`/dev/agent-apps/${agentAppId.value}`, {
      status: form.value.status,
      discount: form.value.discount,
    })

    await api.put(`/dev/agent-apps/${agentAppId.value}/card-types`, {
      card_types: form.value.card_types.map(ct => ({
        card_type_id: ct.card_type_id,
        can_generate: ct.can_generate,
        price: ct.price,
      })),
    })

    toast.success('保存成功')
    router.push('/admin/agent-apps')
  }
  catch (error: any) {
    console.error('保存失败:', error)
    toast.error(error.message || '保存失败')
  }
  finally {
    saving.value = false
  }
}

function goBack() {
  router.push('/admin/agent-apps')
}

function goToView() {
  router.push(`/admin/agent-apps/${agentAppId.value}/view`)
}

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

<template>
  <BasicPage
    title="编辑授权"
    description="修改代理商授权信息"
    :breadcrumbs="[
      { title: '授权管理', href: '/admin/agent-apps' },
      { title: '编辑授权' },
    ]"
    sticky
  >
    <template #actions>
      <UiButton variant="outline" @click="goBack">
        <ArrowLeft class="mr-2 h-4 w-4" />
        返回
      </UiButton>
      <UiButton variant="outline" @click="goToView">
        <Eye class="mr-2 h-4 w-4" />
        查看授权
      </UiButton>
    </template>

    <div v-if="loading" class="flex items-center justify-center py-12">
      <Loader2 class="h-8 w-8 animate-spin text-muted-foreground" />
    </div>

    <div v-else-if="agentApp" 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>基本信息</UiCardTitle>
              <UiCardDescription>
                代理: {{ agentApp.agent_name }} | 应用: {{ agentApp.app_name }}
              </UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="grid grid-cols-2 gap-6">
                <div class="space-y-2">
                  <UiLabel>代理</UiLabel>
                  <div class="flex items-center gap-2">
                    <span class="font-medium">{{ agentApp.agent_name }}</span>
                    <span v-if="agentApp.agent_email" class="text-xs text-muted-foreground">
                      ({{ agentApp.agent_email }})
                    </span>
                  </div>
                </div>
                <div class="space-y-2">
                  <UiLabel>应用</UiLabel>
                  <div class="flex items-center gap-2">
                    <UiBadge variant="secondary">
                      {{ agentApp.app_name }}
                    </UiBadge>
                  </div>
                </div>
              </div>

              <div class="grid grid-cols-2 gap-6">
                <div class="space-y-2">
                  <UiLabel for="status">状态</UiLabel>
                  <UiSelect v-model="form.status">
                    <UiSelectTrigger>
                      <UiSelectValue placeholder="请选择状态" />
                    </UiSelectTrigger>
                    <UiSelectContent>
                      <UiSelectItem value="active">
                        已启用
                      </UiSelectItem>
                      <UiSelectItem value="inactive">
                        已禁用
                      </UiSelectItem>
                    </UiSelectContent>
                  </UiSelect>
                </div>

                <div class="space-y-2">
                  <UiLabel for="discount">折扣</UiLabel>
                  <div class="flex items-center gap-4">
                    <UiNumberField
                      v-model="form.discount"
                      :min="0"
                      :max="1"
                      :step="0.01"
                      class="flex-1"
                    >
                      <UiNumberFieldContent>
                        <UiNumberFieldDecrement />
                        <UiNumberFieldInput />
                        <UiNumberFieldIncrement />
                      </UiNumberFieldContent>
                    </UiNumberField>
                    <span class="text-sm text-muted-foreground w-16">
                      {{ (form.discount * 10).toFixed(1) }}折
                    </span>
                  </div>
                  <p class="text-xs text-muted-foreground">
                    代理商购买卡密的折扣，范围0-1
                  </p>
                </div>
              </div>

              <div class="space-y-2">
                <UiLabel>当前余额</UiLabel>
                <div class="text-2xl font-bold text-primary">
                  ¥{{ (agentApp.balance || 0).toFixed(2) }}
                </div>
              </div>
            </UiCardContent>
          </UiCard>

          <UiCard>
            <UiCardHeader>
              <div class="flex items-center justify-between">
                <div>
                  <UiCardTitle>卡密权限配置</UiCardTitle>
                  <UiCardDescription>配置代理商可生成的卡密类型及价格</UiCardDescription>
                </div>
                <div class="flex gap-2">
                  <UiButton variant="outline" size="sm" @click="selectAll">
                    <CheckCheck class="mr-2 h-4 w-4" />
                    全选
                  </UiButton>
                  <UiButton variant="outline" size="sm" @click="clearAll">
                    <X class="mr-2 h-4 w-4" />
                    清空
                  </UiButton>
                </div>
              </div>
            </UiCardHeader>
            <UiCardContent>
              <div v-if="form.card_types.length > 0">
                <UiTable>
                  <UiTableHeader>
                    <UiTableRow>
                      <UiTableHead class="w-12" />
                      <UiTableHead>卡类名称</UiTableHead>
                      <UiTableHead>计费类型</UiTableHead>
                      <UiTableHead>原价</UiTableHead>
                      <UiTableHead>授权价格</UiTableHead>
                    </UiTableRow>
                  </UiTableHeader>
                  <UiTableBody>
                    <UiTableRow
                      v-for="ct in form.card_types"
                      :key="ct.card_type_id"
                      :class="ct.can_generate ? 'bg-primary/5' : ''"
                      class="cursor-pointer"
                      @click="ct.can_generate = !ct.can_generate"
                    >
                      <UiTableCell>
                        <UiCheckbox
                          :checked="ct.can_generate"
                          @update:checked="ct.can_generate = $event"
                          @click.stop
                        />
                      </UiTableCell>
                      <UiTableCell class="font-medium">
                        {{ ct.name }}
                      </UiTableCell>
                      <UiTableCell>
                        <UiBadge variant="outline">
                          {{ getBillingTypeText(ct.billing_type) }}
                        </UiBadge>
                      </UiTableCell>
                      <UiTableCell>
                        ¥{{ ct.origin_price }}
                      </UiTableCell>
                      <UiTableCell @click.stop>
                        <UiNumberField v-model="ct.price" :min="0" class="w-32">
                          <UiNumberFieldContent>
                            <UiNumberFieldDecrement />
                            <UiNumberFieldInput />
                            <UiNumberFieldIncrement />
                          </UiNumberFieldContent>
                        </UiNumberField>
                      </UiTableCell>
                    </UiTableRow>
                  </UiTableBody>
                </UiTable>
              </div>
              <div v-else class="text-center py-8 text-muted-foreground">
                暂无卡密类型
              </div>
            </UiCardContent>
          </UiCard>
        </div>

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle>统计信息</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="font-medium">{{ form.card_types.length }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">已授权</span>
                  <span class="font-medium text-green-600">
                    {{ form.card_types.filter(ct => ct.can_generate).length }}
                  </span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">未授权</span>
                  <span class="font-medium text-muted-foreground">
                    {{ form.card_types.filter(ct => !ct.can_generate).length }}
                  </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"
                  @click="handleSubmit"
                >
                  <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
                  <Check v-else class="mr-2 h-4 w-4" />
                  保存修改
                </UiButton>
                <UiButton variant="outline" class="w-full" @click="goBack">
                  取消
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
