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

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

const router = useRouter()

interface Agent {
  id: number
  username: string
  email?: string
  status: string
}

interface Application {
  id: number
  name: string
}

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

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

const form = ref({
  agent_id: '',
  application_id: '',
  card_types: [] as Array<{ card_type_id: number, can_generate: boolean, price: number }>,
})

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

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 = []
    form.value.card_types = []
    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 : []
    form.value.card_types = cardTypes.value.map(ct => ({
      card_type_id: ct.id,
      can_generate: false,
      price: ct.price,
    }))
  }
  catch (error) {
    console.error('获取卡类列表失败:', error)
    cardTypes.value = []
    form.value.card_types = []
  }
}

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

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

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

const enabledCardTypesCount = computed(() => {
  return form.value.card_types.filter(ct => ct.can_generate).length
})

function getRechargeTypeText(type: string) {
  const map: Record<string, string> = {
    balance: '余额充值',
    subscription: '订阅充值',
  }
  return map[type] || type
}

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

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

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

async function handleSave() {
  if (!form.value.agent_id) {
    toast.error('请选择代理')
    return
  }
  if (!form.value.application_id) {
    toast.error('请选择应用')
    return
  }

  saving.value = true
  try {
    await api.post('/dev/agent-apps/authorize', {
      agent_id: Number(form.value.agent_id),
      application_id: Number(form.value.application_id),
      card_types: form.value.card_types,
    })
    toast.success('授权成功')
    router.push('/admin/agent-apps')
  }
  catch (error: any) {
    console.error('授权失败:', error)
    toast.error(error.message || '授权失败')
  }
  finally {
    saving.value = false
  }
}

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

<template>
  <BasicPage
    title="新建授权"
    description="为代理分配应用卡密权限"
    :breadcrumbs="[
      { title: '授权管理', href: '/admin/agent-apps' },
      { 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">
                <Share2 class="size-5" />
                基本信息
              </UiCardTitle>
              <UiCardDescription>选择要授权的代理和应用</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel>选择代理</UiLabel>
                <UiSelect v-model="form.agent_id">
                  <UiSelectTrigger>
                    <UiSelectValue placeholder="请选择代理" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem
                      v-for="agent in agents"
                      :key="agent.id"
                      :value="String(agent.id)"
                    >
                      {{ agent.username }}
                      <span v-if="agent.email" class="text-muted-foreground ml-1">({{ agent.email }})</span>
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>

              <div class="space-y-2">
                <UiLabel>选择应用</UiLabel>
                <UiSelect v-model="form.application_id">
                  <UiSelectTrigger>
                    <UiSelectValue placeholder="请选择应用" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem
                      v-for="app in applications"
                      :key="app.id"
                      :value="String(app.id)"
                    >
                      {{ app.name }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>
            </UiCardContent>
          </UiCard>

          <UiCard v-if="cardTypes.length > 0">
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Key class="size-5" />
                卡密权限
              </UiCardTitle>
              <UiCardDescription>配置代理可生成的卡密类型及价格</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-4">
              <div class="flex gap-2">
                <UiButton variant="outline" size="sm" @click="selectAllCardTypes">
                  <CheckCheck class="mr-2 h-4 w-4" />
                  全选
                </UiButton>
                <UiButton variant="outline" size="sm" @click="clearAllCardTypes">
                  <X class="mr-2 h-4 w-4" />
                  清空
                </UiButton>
              </div>

              <div class="border rounded-lg">
                <UiTable>
                  <UiTableHeader>
                    <UiTableRow>
                      <UiTableHead class="w-12" />
                      <UiTableHead>卡类名称</UiTableHead>
                      <UiTableHead>充值类型</UiTableHead>
                      <UiTableHead>原价</UiTableHead>
                      <UiTableHead>授权价格</UiTableHead>
                    </UiTableRow>
                  </UiTableHeader>
                  <UiTableBody>
                    <UiTableRow
                      v-for="(ct, index) in form.card_types"
                      :key="ct.card_type_id"
                      :class="ct.can_generate ? 'bg-primary/10' : ''"
                      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">
                        {{ cardTypes[index]?.name || `卡类 #${ct.card_type_id}` }}
                      </UiTableCell>
                      <UiTableCell>
                        <UiBadge variant="outline">
                          {{ getRechargeTypeText(cardTypes[index]?.recharge_type || '') }}
                        </UiBadge>
                      </UiTableCell>
                      <UiTableCell>
                        ¥{{ cardTypes[index]?.price || 0 }}
                      </UiTableCell>
                      <UiTableCell @click.stop>
                        <UiNumberField v-model="ct.price" :min="0" class="w-28">
                          <UiNumberFieldContent>
                            <UiNumberFieldDecrement />
                            <UiNumberFieldInput />
                            <UiNumberFieldIncrement />
                          </UiNumberFieldContent>
                        </UiNumberField>
                      </UiTableCell>
                    </UiTableRow>
                  </UiTableBody>
                </UiTable>
              </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>{{ selectedAgent?.username || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">应用</span>
                  <span>{{ selectedApplication?.name || '-' }}</span>
                </div>
                <div v-if="cardTypes.length > 0" class="flex justify-between text-sm">
                  <span class="text-muted-foreground">卡密权限</span>
                  <span>{{ enabledCardTypesCount }}/{{ cardTypes.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 || !isFormValid"
                  @click="handleSave"
                >
                  <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
                  <Share2 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>
