<script setup lang="ts">
import { Check, Eye, Loader2, 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()

const userId = computed(() => route.params.id as string)
const loading = ref(true)
const saving = ref(false)

const form = ref({
  username: '',
  email: '',
  password: '',
})

async function fetchUser() {
  loading.value = true
  try {
    const data = await api.get<any>(`/agent/users/${userId.value}`)
    const user = data?.user || data
    if (user) {
      form.value.username = user.username || ''
      form.value.email = user.email || ''
    }
  }
  catch (error) {
    console.error('获取用户信息失败:', error)
    toast.error(t('agent.users.edit.failed'))
  }
  finally {
    loading.value = false
  }
}

async function handleSave() {
  if (!form.value.username) {
    toast.error(t('agent.users.edit.usernameRequired'))
    return
  }

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

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

    await api.put(`/agent/users/${userId.value}`, payload)
    toast.success(t('agent.users.edit.success'))
    router.push('/agent/users')
  }
  catch (error: any) {
    console.error('更新用户失败:', error)
    toast.error(error.message || t('agent.users.edit.failed'))
  }
  finally {
    saving.value = false
  }
}

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

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

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

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

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Eye class="size-5" />
                {{ t('agent.users.edit.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('agent.users.edit.usernameLabel') }}</span>
                  <span>{{ form.username || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('agent.users.edit.emailLabel') }}</span>
                  <span>{{ form.email || '-' }}</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('agent.users.edit.saveBtn') }}
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  {{ t('agent.users.edit.cancel') }}
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
