<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({
  agent_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.agent_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/invite`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        agent_id: Number(form.value.agent_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="agent_id">
              代理商ID
            </UiLabel>
            <UiInput
              id="agent_id"
              v-model="form.agent_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>
