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

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

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

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

const agentId = computed(() => route.params.id as string)
const loading = ref(true)
const saving = ref(false)
const agents = ref<Agent[]>([])

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

async function fetchAgent() {
  loading.value = true
  try {
    const data = await api.get<any>(`/dev/agents/${agentId.value}`)
    const agent = data?.agent || data
    if (agent) {
      form.value.username = agent.username || ''
      form.value.email = agent.email || ''
      form.value.parent_agent_id = agent.parent_agent_id ? String(agent.parent_agent_id) : 'none'
      form.value.can_create_agent = agent.can_create_agent || false
      form.value.balance = agent.balance || 0
    }
  }
  catch (error) {
    console.error('获取代理信息失败:', error)
    toast.error(t('admin.agents.editFailed'))
  }
  finally {
    loading.value = false
  }
}

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 && form.value.parent_agent_id !== 'none') {
    return agents.value.find(a => String(a.id) === form.value.parent_agent_id)
  }
  return null
})

async function handleSave() {
  if (!form.value.username) {
    toast.error(t('admin.agents.create.usernameRequired'))
    return
  }

  saving.value = true
  try {
    const payload: any = {
      username: form.value.username,
      can_create_agent: form.value.can_create_agent,
      balance: form.value.balance,
    }

    if (form.value.email) {
      payload.email = form.value.email
    }

    if (form.value.password) {
      payload.password = form.value.password
    }

    if (form.value.parent_agent_id && form.value.parent_agent_id !== 'none') {
      payload.parent_agent_id = Number.parseInt(form.value.parent_agent_id)
    }

    await api.put(`/dev/agents/${agentId.value}`, payload)
    toast.success(t('admin.agents.editSuccess'))
    router.push('/admin/agents')
  }
  catch (error: any) {
    console.error('更新代理失败:', error)
    toast.error(error.message || t('admin.agents.editFailed'))
  }
  finally {
    saving.value = false
  }
}

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

<template>
  <BasicPage
    :title="t('admin.agents.edit')"
    :description="t('admin.agents.create.description')"
    :breadcrumbs="[
      { title: t('admin.agents.title'), href: '/admin/agents' },
      { title: t('admin.agents.edit') },
    ]"
    sticky
  >
    <div v-if="loading" class="flex items-center justify-center py-12">
      <Loader2 class="size-8 animate-spin text-muted-foreground" />
    </div>

    <div v-else 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">
                  留空则不修改密码
                </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>
              </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>
              </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>
            </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">{{ 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"
                  @click="handleSave"
                >
                  <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
                  <Check v-else class="mr-2 h-4 w-4" />
                  {{ t('admin.agents.create.saveBtn') || '保存修改' }}
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  {{ t('admin.agents.create.cancel') }}
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
