<template>
  <Stack gap="8">
    <Section variant="plain">
      <Stack gap="4">
          <Stack direction="row" align="center" justify="between">
            <Heading :level="1">{{ $t('dashboard.profile') }}</Heading>
            <NuxtLink
              :to="localePath('/dashboard/profile/token')"
              class="inline-flex items-center gap-2 text-primary hover:text-primary-hover font-semibold text-sm"
            >
              <Icon name="lucide:bug" size="16" />
              Debug токенов
            </NuxtLink>
          </Stack>

          <Alert v-if="hasError" variant="error">
            <Stack gap="1">
              <Heading :level="4" weight="semibold">{{ $t('common.error') }}</Heading>
              <Text tone="muted">{{ error }}</Text>
            </Stack>
          </Alert>

          <Stack v-if="isLoading" align="center" justify="center" gap="3">
            <Spinner />
            <Text tone="muted">Загружаем профиль...</Text>
          </Stack>

          <template v-else>
            <Card padding="lg">
              <Grid :cols="1" :lg="3" :gap="8">
                <GridItem :lg="2">
                  <Stack gap="4">
                    <form @submit.prevent="updateProfile">
                      <Stack gap="4">
                        <Input
                          v-model="profileForm.firstName"
                          type="text"
                          :label="$t('profile.first_name')"
                          :placeholder="$t('profile.first_name_placeholder')"
                        />
                        <Input
                          v-model="profileForm.lastName"
                          type="text"
                          :label="$t('profile.last_name')"
                          :placeholder="$t('profile.last_name_placeholder')"
                        />
                        <Input
                          v-model="profileForm.phone"
                          type="tel"
                          :label="$t('profile.phone')"
                          :placeholder="$t('profile.phone_placeholder')"
                        />
                        <Button type="submit" :full-width="true" :disabled="isUpdating">
                          <template v-if="isUpdating">{{ $t('profile.saving') }}...</template>
                          <template v-else>{{ $t('profile.save') }}</template>
                        </Button>
                      </Stack>
                    </form>
                  </Stack>
                </GridItem>

                <GridItem>
                  <Stack gap="6">
                    <Stack gap="3" align="center">
                      <Heading :level="3">{{ $t('profile.avatar') }}</Heading>
                      <UserAvatar
                        :userId="userData?.id"
                        :firstName="userData?.firstName"
                        :lastName="userData?.lastName"
                        :avatarId="userData?.avatarId"
                        @avatar-changed="handleAvatarChange"
                      />
                    </Stack>

                    <Stack gap="3">
                      <Heading :level="3">{{ $t('profile.language') }}</Heading>
                      <LangSwitcher variant="dark" />
                    </Stack>
                  </Stack>
                </GridItem>
              </Grid>
            </Card>
          </template>
        </Stack>
    </Section>
  </Stack>
</template>

<script setup>
definePageMeta({
  middleware: ['auth-oidc']
})

const localePath = useLocalePath()
const { getIdTokenClaims } = useAuth()
const { execute, mutate } = useGraphQL()

const userData = ref(null)
const isLoading = ref(true)
const hasError = ref(false)
const error = ref('')
const isUpdating = ref(false)

const profileForm = reactive({
  firstName: '',
  lastName: '',
  phone: ''
})

const loadUserData = async () => {
  try {
    isLoading.value = true
    hasError.value = false

    const { GetMeProfileDocument } = await import('~/composables/graphql/user/teams-generated')
    const result = await execute(GetMeProfileDocument, {}, 'user', 'teams')

    if (result.me) {
      userData.value = result.me
      profileForm.firstName = result.me.firstName || ''
      profileForm.lastName = result.me.lastName || ''
      profileForm.phone = result.me.phone || ''
    }
  } catch (err) {
    hasError.value = true
    error.value = err?.message || 'Ошибка загрузки профиля'
  } finally {
    isLoading.value = false
  }
}

const updateProfile = async () => {
  try {
    isUpdating.value = true

    const { UpdateUserDocument } = await import('~/composables/graphql/user/teams-generated')
    const result = await mutate(UpdateUserDocument, {
      userId: userData.value.id,
      input: {
        firstName: profileForm.firstName,
        lastName: profileForm.lastName,
        phone: profileForm.phone,
      },
    }, 'user', 'teams')

    if (result?.updateUser?.user) {
      userData.value = result.updateUser.user
    }
  } catch (err) {
    hasError.value = true
    error.value = err?.message || 'Ошибка сохранения профиля'
  } finally {
    isUpdating.value = false
  }
}

const handleAvatarChange = async () => {
  await loadUserData()
}

onMounted(async () => {
  await loadUserData()
  await getIdTokenClaims()
})
</script>
