<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()

interface Application {
  id: string
  name: string
}

const userId = computed(() => route.params.id as string)
const loading = ref(true)
const saving = ref(false)
const applications = ref<Application[]>([])

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

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

async function fetchApplications() {
  try {
    const data = await api.get<{ applications: Application[] }>('/dev/applications')
    applications.value = Array.isArray(data?.applications) ? data.applications : []
  }
  catch (error) {
    console.error('获取应用列表失败:', error)
  }
}

const selectedApplication = computed(() => {
  if (form.value.application_id) {
    return applications.value.find(app => String(app.id) === form.value.application_id)
  }
  return null
})

async function handleSave() {
  if (!form.value.username) {
    toast.error(t('admin.users.edit.usernameRequired'))
    return
  }
  if (!form.value.email) {
    toast.error(t('admin.users.edit.emailRequired'))
    return
  }
  if (!form.value.application_id) {
    toast.error(t('admin.users.edit.applicationRequired'))
    return
  }

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

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

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

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

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

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

              <div class="space-y-2">
                <UiLabel for="password">
                  {{ t('admin.users.edit.password') }}
                </UiLabel>
                <UiInput id="password" v-model="form.password" type="password" :placeholder="t('admin.users.edit.passwordPlaceholder')" />
                <p class="text-xs text-muted-foreground">
                  {{ t('admin.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('admin.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('admin.users.edit.app') }}</span>
                  <span>{{ selectedApplication?.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.users.edit.usernameLabel') }}</span>
                  <span>{{ form.username || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.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 || !form.email || !form.application_id"
                  @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.users.edit.saveBtn') }}
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  {{ t('admin.users.edit.cancel') }}
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
