<template>
  <div>
    <CatalogPage
      :items="[]"
      :loading="false"
      :use-server-clustering="false"
      map-id="profile-map"
      point-color="#10b981"
      :show-panel="false"
      :hide-view-toggle="true"
    />

    <!-- Bottom Sheet -->
    <div class="fixed inset-x-0 bottom-0 z-50 flex flex-col" style="height: 70vh">
      <!-- Glass sheet -->
      <div class="relative flex-1 bg-black/40 backdrop-blur-xl rounded-t-2xl border-t border-white/20 shadow-2xl overflow-hidden">
        <!-- Drag handle -->
        <div class="flex justify-center py-2">
          <div class="w-12 h-1.5 bg-white/30 rounded-full" />
        </div>

        <!-- Header -->
        <div class="px-6 pb-4 border-b border-white/10">
          <!-- Error state -->
          <div v-if="hasError" 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>

          <!-- Profile header -->
          <template v-else>
            <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="lg"
                @avatar-changed="handleAvatarChange"
              />
              <div>
                <div class="font-bold text-lg text-white">
                  {{ userData?.firstName || '' }} {{ userData?.lastName || '' }}
                </div>
                <div class="text-xs text-white/50">{{ $t('dashboard.profile') }}</div>
              </div>
            </div>
          </template>
        </div>

        <!-- Scrollable content -->
        <div v-if="!hasError" class="overflow-y-auto h-[calc(70vh-120px)] px-6 py-4">
          <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
            <!-- Profile form -->
            <div class="bg-white/5 rounded-xl p-4 border border-white/10">
              <div class="font-semibold text-white mb-4 flex items-center gap-2">
                <Icon name="lucide:user" size="18" />
                {{ $t('profile.personal_info', 'Personal Information') }}
              </div>

              <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>
            </div>

            <!-- Settings -->
            <div class="bg-white/5 rounded-xl p-4 border border-white/10">
              <div class="font-semibold text-white mb-4 flex items-center gap-2">
                <Icon name="lucide:settings" size="18" />
                {{ $t('profile.settings', 'Settings') }}
              </div>

              <div class="space-y-3">
                <!-- Debug tokens link -->
                <NuxtLink
                  :to="localePath('/clientarea/profile/debug-tokens')"
                  class="flex items-center gap-3 p-3 bg-white/5 rounded-lg hover:bg-white/10 transition-colors"
                >
                  <Icon name="lucide:bug" size="18" class="text-white/50" />
                  <div>
                    <div class="text-sm text-white">{{ t('clientProfile.actions.debugTokens') }}</div>
                    <div class="text-xs text-white/50">{{ t('clientProfile.actions.debugTokensDesc', 'View authentication tokens') }}</div>
                  </div>
                </NuxtLink>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</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>
