<template>
  <CatalogPage
    :items="[]"
    :loading="isLoading"
    :use-server-clustering="false"
    map-id="profile-map"
    point-color="#10b981"
    :show-panel="true"
    panel-width="w-96"
    :hide-view-toggle="true"
  >
    <template #panel>
      <!-- Error state -->
      <div v-if="hasError" class="p-4">
        <div class="bg-error/20 border border-error/30 rounded-lg p-4">
          <div class="font-semibold text-white mb-2">{{ $t('common.error') }}</div>
          <div class="text-sm text-white/70">{{ error }}</div>
        </div>
      </div>

      <template v-else>
        <!-- Panel header -->
        <div class="p-4 border-b border-white/10 flex-shrink-0">
          <div class="flex items-center gap-3">
            <UserAvatar
              :userId="userData?.id ?? undefined"
              :firstName="userData?.firstName ?? undefined"
              :lastName="userData?.lastName ?? undefined"
              :avatarId="userData?.avatarId ?? undefined"
              size="md"
              @avatar-changed="handleAvatarChange"
            />
            <div class="flex-1 min-w-0">
              <div class="font-semibold text-white truncate">
                {{ userData?.firstName || '' }} {{ userData?.lastName || '' }}
              </div>
              <div class="text-xs text-white/50">{{ $t('dashboard.profile') }}</div>
            </div>
          </div>
        </div>

        <!-- Profile form -->
        <div class="flex-1 overflow-y-auto p-4">
          <form class="space-y-4" @submit.prevent="updateProfile">
            <!-- First name -->
            <div>
              <label class="block text-xs text-white/50 mb-1">{{ $t('profile.first_name') }}</label>
              <input
                v-model="profileForm.firstName"
                type="text"
                :placeholder="$t('profile.first_name_placeholder')"
                class="input input-sm w-full bg-white/10 border-white/20 text-white placeholder:text-white/30"
              />
            </div>

            <!-- Last name -->
            <div>
              <label class="block text-xs text-white/50 mb-1">{{ $t('profile.last_name') }}</label>
              <input
                v-model="profileForm.lastName"
                type="text"
                :placeholder="$t('profile.last_name_placeholder')"
                class="input input-sm w-full bg-white/10 border-white/20 text-white placeholder:text-white/30"
              />
            </div>

            <!-- Phone -->
            <div>
              <label class="block text-xs text-white/50 mb-1">{{ $t('profile.phone') }}</label>
              <input
                v-model="profileForm.phone"
                type="tel"
                :placeholder="$t('profile.phone_placeholder')"
                class="input input-sm w-full bg-white/10 border-white/20 text-white placeholder:text-white/30"
              />
            </div>

            <!-- Save button -->
            <button
              type="submit"
              class="btn btn-sm w-full bg-primary border-primary text-primary-content hover:bg-primary/80"
              :disabled="isUpdating"
            >
              <template v-if="isUpdating">{{ $t('profile.saving') }}...</template>
              <template v-else>{{ $t('profile.save') }}</template>
            </button>
          </form>

          <!-- Debug tokens link -->
          <div class="mt-6 pt-4 border-t border-white/10">
            <NuxtLink
              :to="localePath('/clientarea/profile/debug-tokens')"
              class="flex items-center gap-2 text-sm text-white/50 hover:text-white transition-colors"
            >
              <Icon name="lucide:bug" size="14" />
              {{ t('clientProfile.actions.debugTokens') }}
            </NuxtLink>
          </div>
        </div>
      </template>
    </template>
  </CatalogPage>
</template>

<script setup lang="ts">
definePageMeta({
  layout: 'topnav',
  middleware: ['auth-oidc']
})

const localePath = useLocalePath()
const { t } = useI18n()
const { mutate } = useGraphQL()

const userData = useState<{
  id?: string
  firstName?: string
  lastName?: string
  phone?: string | null
  avatarId?: string | null
} | null>('me', () => null)
const isLoading = ref(true)
const hasError = ref(false)
const error = ref('')
const isUpdating = ref(false)
const avatarDraftId = ref<string | null>(null)

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

const syncProfileForm = () => {
  if (!userData.value) {
    hasError.value = true
    error.value = t('clientProfile.error.load')
    isLoading.value = false
    return
  }

  hasError.value = false
  error.value = ''
  profileForm.firstName = userData.value.firstName || ''
  profileForm.lastName = userData.value.lastName || ''
  profileForm.phone = userData.value.phone || ''
  avatarDraftId.value = userData.value.avatarId || null
  isLoading.value = false
}

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

    if (!userData.value?.id) {
      throw new Error(t('clientProfile.error.load'))
    }

    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,
        avatarId: avatarDraftId.value || null
      },
    }, 'user', 'teams')

    if (result?.updateUser?.user) {
      const user = result.updateUser.user
      userData.value = {
        id: user.id ?? undefined,
        firstName: user.firstName ?? undefined,
        lastName: user.lastName ?? undefined,
        phone: user.phone,
        avatarId: user.avatarId
      }
      avatarDraftId.value = userData.value.avatarId || avatarDraftId.value
    }
  } catch (err: unknown) {
    hasError.value = true
    error.value = (err as Error)?.message || t('clientProfile.error.save')
  } finally {
    isUpdating.value = false
  }
}

const handleAvatarChange = async (newAvatarId?: string) => {
  if (!newAvatarId) return
  avatarDraftId.value = newAvatarId
}

watch(userData, () => {
  syncProfileForm()
}, { immediate: true })
</script>
