<script setup lang="ts">
import { Loader2, Receipt, Settings2, UserPlus } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

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

const router = useRouter()
const { t } = useI18n()

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

const saving = ref(false)
const agents = ref<Agent[]>([])

const form = ref({
  username: '',
  email: '',
  password: '',
  parent_agent_id: '',
  can_create_agent: false,
  can_view_cloud_data: false,
  balance: 0,
})

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

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

async function handleCreate() {
  if (!form.value.username) {
    toast.error(t('admin.agents.create.usernameRequired'))
    return
  }
  if (!form.value.password) {
    toast.error(t('admin.agents.create.passwordRequired'))
    return
  }
  if (form.value.password.length < 6) {
    toast.error(t('admin.agents.create.passwordMinLength'))
    return
  }

  saving.value = true
  try {
    const payload: any = {
      username: form.value.username,
      password: form.value.password,
      can_create_agent: form.value.can_create_agent,
      can_view_cloud_data: form.value.can_view_cloud_data,
      balance: form.value.balance,
    }
    
    if (form.value.email) {
      payload.email = form.value.email
    }
    
    if (form.value.parent_agent_id && form.value.parent_agent_id !== 'none') {
      payload.parent_agent_id = parseInt(form.value.parent_agent_id)
    }

    await api.post('/dev/agents', payload)
    toast.success(t('admin.agents.create.createSuccess'))
    router.push('/admin/agents')
  }
  catch (error: any) {
    console.error('创建代理失败:', error)
    toast.error(error.message || t('admin.agents.create.createFailed'))
  }
  finally {
    saving.value = false
  }
}

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

<template>
  <BasicPage
    :title="t('admin.agents.create.title')"
    :description="t('admin.agents.create.description')"
    :breadcrumbs="[
      { title: t('admin.agents.title'), href: '/admin/agents' },
      { title: t('admin.agents.create.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">
                <UserPlus class="size-5" />
                {{ t('admin.agents.create.basicInfo') }}
              </UiCardTitle>
              <UiCardDescription>{{ t('admin.agents.create.basicInfoDesc') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel for="username">
                  {{ t('admin.agents.form.username') }}
                </UiLabel>
                <UiInput
                  id="username"
                  v-model="form.username"
                  :placeholder="t('admin.agents.form.usernamePlaceholder')"
                />
              </div>

              <div class="space-y-2">
                <UiLabel for="email">
                  {{ t('admin.agents.form.email') }}
                </UiLabel>
                <UiInput
                  id="email"
                  v-model="form.email"
                  type="email"
                  :placeholder="t('admin.agents.form.emailPlaceholder')"
                />
              </div>

              <div class="space-y-2">
                <UiLabel for="password">
                  {{ t('admin.agents.form.password') }}
                </UiLabel>
                <UiInput
                  id="password"
                  v-model="form.password"
                  type="password"
                  :placeholder="t('admin.agents.form.passwordPlaceholder')"
                />
                <p class="text-xs text-muted-foreground">
                  {{ t('admin.agents.create.passwordHint') }}
                </p>
              </div>
            </UiCardContent>
          </UiCard>

          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Settings2 class="size-5" />
                {{ t('admin.agents.create.agentConfig') }}
              </UiCardTitle>
              <UiCardDescription>{{ t('admin.agents.create.agentConfigDesc') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel for="parent_agent">
                  {{ t('admin.agents.form.parentAgent') }}
                </UiLabel>
                <UiSelect v-model="form.parent_agent_id">
                  <UiSelectTrigger>
                    <UiSelectValue :placeholder="t('admin.agents.form.selectParentAgent')" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem value="none">
                      {{ t('admin.agents.form.noParent') }}
                    </UiSelectItem>
                    <UiSelectItem
                      v-for="agent in agents"
                      :key="agent.id"
                      :value="String(agent.id)"
                    >
                      {{ agent.username }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
                <p class="text-xs text-muted-foreground">
                  {{ t('admin.agents.create.parentAgentHint') }}
                </p>
              </div>

              <div class="space-y-2">
                <UiLabel for="balance">
                  {{ t('admin.agents.form.balance') }}
                </UiLabel>
                <div class="flex items-center gap-4">
                  <UiNumberField
                    v-model="form.balance"
                    :min="0"
                    :step="0.01"
                    class="flex-1 max-w-[200px]"
                  >
                    <UiNumberFieldContent>
                      <UiNumberFieldDecrement />
                      <UiNumberFieldInput />
                      <UiNumberFieldIncrement />
                    </UiNumberFieldContent>
                  </UiNumberField>
                  <span class="text-sm text-muted-foreground">¥</span>
                </div>
                <p class="text-xs text-muted-foreground">
                  {{ t('admin.agents.form.balancePlaceholder') }}
                </p>
              </div>

              <div class="flex items-center justify-between">
                <div class="space-y-0.5">
                  <UiLabel>{{ t('admin.agents.form.canCreateAgent') }}</UiLabel>
                  <p class="text-xs text-muted-foreground">
                    {{ t('admin.agents.create.canCreateAgentHint') }}
                  </p>
                </div>
                <UiSwitch v-model="form.can_create_agent" />
              </div>

              <div class="flex items-center justify-between">
                <div class="space-y-0.5">
                  <UiLabel>云端数据权限</UiLabel>
                  <p class="text-xs text-muted-foreground">
                    允许代理查看云端数据（只读）
                  </p>
                </div>
                <UiSwitch v-model="form.can_view_cloud_data" />
              </div>
            </UiCardContent>
          </UiCard>
        </div>

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Receipt class="size-5" />
                {{ t('admin.agents.create.preview') }}
              </UiCardTitle>
            </UiCardHeader>
            <UiCardContent class="space-y-4">
              <div class="space-y-3">
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.agents.form.username') }}</span>
                  <span>{{ form.username || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.agents.form.email') }}</span>
                  <span>{{ form.email || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.agents.form.canCreateAgent') }}</span>
                  <span>{{ form.can_create_agent ? t('common.yes') : t('common.no') }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">云端数据权限</span>
                  <span>{{ form.can_view_cloud_data ? t('common.yes') : t('common.no') }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.agents.form.parentAgent') }}</span>
                  <span>{{ selectedParentAgent?.username || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.agents.form.balance') }}</span>
                  <span>¥{{ form.balance.toFixed(2) }}</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 || !form.username || !form.password"
                  @click="handleCreate"
                >
                  <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
                  <UserPlus v-else class="mr-2 h-4 w-4" />
                  {{ t('admin.agents.form.create') }}
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  {{ t('admin.agents.create.cancel') }}
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
