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

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

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

const route = useRoute()
const router = useRouter()
const API_BASE = 'http://localhost:8080/api/v1'

const loading = ref(true)
const saving = ref(false)
const agentApp = ref<AgentApp | null>(null)

const form = ref({
  discount: 1.0,
  status: 'active',
})

async function fetchAgentApp() {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`${API_BASE}/dev/agent-apps/${route.params.id}`, {
      headers: { Authorization: `Bearer ${token}` },
    })
    const data = await response.json()
    if (data.code === 200 && data.agent_app) {
      agentApp.value = data.agent_app
      form.value = {
        discount: data.agent_app.discount,
        status: data.agent_app.status,
      }
    }
    else {
      toast.error('获取授权信息失败')
      router.push('/admin/agent-apps')
    }
  }
  catch (error) {
    console.error('获取授权信息失败:', error)
    toast.error('获取授权信息失败')
    router.push('/admin/agent-apps')
  }
  finally {
    loading.value = false
  }
}

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

  saving.value = true
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`${API_BASE}/dev/agent-apps/${route.params.id}`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(form.value),
    })

    const data = await response.json()
    if (data.code === 200) {
      toast.success('保存成功')
      router.push('/admin/agent-apps')
    }
    else {
      toast.error(data.message || '保存失败')
    }
  }
  catch (error) {
    console.error('保存失败:', error)
    toast.error('保存失败')
  }
  finally {
    saving.value = false
  }
}

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

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

<template>
  <BasicPage
    title="编辑授权"
    description="修改代理商授权信息"
  >
    <template #actions>
      <UiButton variant="outline" @click="goBack">
        <ArrowLeft 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="max-w-2xl">
      <UiCard>
        <UiCardHeader>
          <UiCardTitle>授权信息</UiCardTitle>
          <UiCardDescription>
            代理商: {{ agentApp.agent_name }} | 应用: {{ agentApp.app_name }}
          </UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-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">
              <UiInput
                id="discount"
                v-model.number="form.discount"
                type="number"
                step="0.01"
                min="0"
                max="1"
                class="flex-1"
              />
              <span class="text-sm text-muted-foreground w-20">
                {{ (form.discount * 10).toFixed(1) }}折
              </span>
            </div>
            <p class="text-xs text-muted-foreground">
              代理商购买卡密的折扣，范围0-1
            </p>
          </div>

          <div class="space-y-2">
            <UiLabel>当前余额</UiLabel>
            <div class="text-2xl font-bold">
              ¥{{ agentApp.balance.toFixed(2) }}
            </div>
            <UiButton
              variant="outline"
              size="sm"
              @click="router.push(`/admin/agent-apps/${route.params.id}/recharge`)"
            >
              <Wallet class="mr-2 h-4 w-4" />
              充值余额
            </UiButton>
          </div>
        </UiCardContent>
        <UiCardFooter class="flex justify-end gap-2">
          <UiButton variant="outline" @click="goBack">
            取消
          </UiButton>
          <UiButton :disabled="saving" @click="handleSubmit">
            <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
            保存
          </UiButton>
        </UiCardFooter>
      </UiCard>
    </div>
  </BasicPage>
</template>
