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

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

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

const saving = ref(false)
const applications = ref<Array<{ id: number, name: string }>>([])

const form = ref({
  admin_id: '',
  application_id: '',
  message: '',
})

async function fetchApplications() {
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`${API_BASE}/dev/applications`, {
      headers: { Authorization: `Bearer ${token}` },
    })
    const data = await response.json()
    if (data.code === 200) {
      applications.value = data.applications || []
    }
  }
  catch (error) {
    console.error('获取应用列表失败:', error)
  }
}

async function handleSubmit() {
  if (!form.value.admin_id) {
    toast.error('请输入管理员ID')
    return
  }
  if (!form.value.application_id) {
    toast.error('请选择应用')
    return
  }

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

    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(() => {
  fetchApplications()
})
</script>

<template>
  <BasicPage
    title="申请授权"
    description="向管理员申请应用授权"
  >
    <template #actions>
      <UiButton variant="outline" @click="goBack">
        <ArrowLeft class="mr-2 h-4 w-4" />
        返回
      </UiButton>
    </template>

    <div class="max-w-2xl">
      <UiCard>
        <UiCardHeader>
          <UiCardTitle>申请信息</UiCardTitle>
          <UiCardDescription>
            填写以下信息向管理员申请应用授权
          </UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="space-y-6">
          <div class="space-y-2">
            <UiLabel for="admin_id">
              管理员ID
            </UiLabel>
            <UiInput
              id="admin_id"
              v-model="form.admin_id"
              type="number"
              placeholder="请输入管理员ID"
            />
            <p class="text-xs text-muted-foreground">
              请向管理员索取其ID
            </p>
          </div>

          <div class="space-y-2">
            <UiLabel for="application_id">
              选择应用
            </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>

          <div class="space-y-2">
            <UiLabel for="message">
              申请说明
            </UiLabel>
            <UiTextarea
              id="message"
              v-model="form.message"
              placeholder="请输入申请说明（可选）"
              :rows="4"
            />
          </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>
