<script lang="ts" setup>
import AdataLogo from '#adata-ui/icons/adata-logo.vue'
import AColorMode from '#adata-ui/components/features/color-mode/AColorMode.client.vue'
import Arrow from '#adata-ui/icons/chevron/chevron-down.vue'
import HeaderLink from './HeaderLink.vue'
import ProfileMenu from '#adata-ui/components/navigation/header/ProfileMenu.vue'
import IconLogout from '#adata-ui/icons/logout.vue'
import TopHeader from '#adata-ui/components/navigation/header/TopHeader.vue'
import LangSwitcher from '#adata-ui/components/features/lang-switcher/lang-switcher.vue'
import AChangeVersion from '#adata-ui/components/features/сhange-version/AChangeVersion.vue'
import Logo from '#adata-ui/icons/logo.vue'
import type { ProjectKeys } from '#adata-ui/components/navigation/header/types'
import { useContacts, useCurrentModule } from '#adata-ui/composables/projectState'
import { navigateToLocalizedPage, buildLocalizedUrl } from '#adata-ui/utils/localizedNavigation'

defineOptions({ name: 'AHeader' })

interface Props {
  replenish?: string
  hasNotification?: boolean
  email: string | undefined
  rate: string
  daysRemaining: number
  limitRemaining: number
  balance: number
  isAuthenticated: boolean
  showLogIn?: boolean
  mobileHeaderType?: 'search' | 'default'
  module?: ProjectKeys
  oldVersion?: string
}

const props = withDefaults(defineProps<Props>(), {
  limitRemaining: 0,
  daysRemaining: 0,
  balance: 0,
  rate: 'Базовый',
  showLogIn: true,
  mobileHeaderType: 'default',
  module: 'pk'
})

const emit = defineEmits(['logout', 'search', 'login'])

const { t } = useI18n()
const { locale } = useI18n()

useCurrentModule().value = props.module
const appConfig = useAppConfig()
const { myLayer }: any = useAppConfig()

const langIsOn = appConfig.myLayer.langIsOn
const contacts = ref(useContacts())
const goAuth = () => {
  if (window) {
    emit('login')
    let fullPath = encodeURIComponent(window.location.toString())
    if (fullPath.includes('basic-info')) {
      fullPath = fullPath.replace('%2Fcounterparty%2Fmain', '').replace('%2Fbasic-info', '')
    }

    navigateToLocalizedPage({
      locale,
      projectUrl: myLayer.loginUrl.slice(0, -1),
      path: `/?url=${fullPath}`,
      target: '_self'
    })
  }
}

const goToAnotherModule = () => {
  location.href = buildLocalizedUrl(locale.value, myLayer.landingUrl, '')
}

const fetchContacts = async () => {
  try {
    const response = await fetch(
      'https://pk-api.adata.kz/api/v1/data/counterparty/contacts/sales-department'
    )
    const { data } = await response.json()
    contacts.value = data
  } catch (e) {
    console.error(e.message)
  }
}

onBeforeMount(() => {
  fetchContacts()
})
</script>

<template>
  <div>
    <top-header
      :days-remaining="daysRemaining"
      :is-authenticated="isAuthenticated"
      :module-name="module"
      :limit-remaining="limitRemaining"
    />
    <header
      class="relative h-16 border-b border-deepblue-900/10 bg-white dark:border-gray-200/10 dark:bg-gray-900"
    >
      <div class="a-container mobile-padding flex h-full items-center justify-between gap-2">
        <!--        Desktop hidden-->
        <section id="mobile-header" class="grow lg:hidden">
          <div v-if="mobileHeaderType === 'default'" class="flex justify-center">
            <nuxt-link class="text-deepblue dark:text-[#E3E5E8]" @click="goToAnotherModule">
              <span class="visually-hidden"> Сервисы Adata.kz</span>

              <adata-logo :font-controlled="false" filled />
            </nuxt-link>
          </div>
          <div
            v-else-if="mobileHeaderType === 'search'"
            class="flex w-full items-center gap-2 bg-white dark:bg-gray-900 lg:hidden"
          >
            <logo class="dark:text-gray-200" @click="goToAnotherModule" />
            <button
              class="flex w-full items-center gap-2 rounded bg-gray-50 px-4 py-1.5 dark:bg-gray-800 dark:text-gray-500"
              @click="$emit('search')"
            >
              <a-icon-search />
              <span class="body-400">Найти</span>
            </button>
          </div>
        </section>
        <div class="lg:hidden">
          <lang-switcher v-if="langIsOn || module === 'fea'" class="lg:hidden" />
        </div>
        <!--Mobile hidden-->
        <nav class="hidden items-center gap-4 lg:flex">
          <nuxt-link-locale
            aria-label="Adata-logo"
            :to="buildLocalizedUrl(locale, myLayer.landingUrl)"
            class="text-deepblue cursor-pointer dark:text-[#E3E5E8]"
            @click="goToAnotherModule"
          >
            <adata-logo :font-controlled="false" filled />
          </nuxt-link-locale>
          <header-link />
        </nav>
        <div class="text-deepblue hidden items-center gap-4 dark:text-[#E3E5E8] lg:flex">
          <!--Mobile hidden-->
          <div class="hidden items-center gap-4 lg:flex">
            <a-change-version v-if="oldVersion" :url="oldVersion" />
            <a-color-mode />
            <lang-switcher v-if="langIsOn || module === 'fea'" />
          </div>

          <a-dropdown placement="right" v-show="isAuthenticated">
            <template #default="{ onExpand, expanded }">
              <div
                class="hidden cursor-pointer items-center gap-2 text-sm font-semibold lg:flex"
                @click.stop="onExpand"
              >
                <span>{{ email }}</span>
                <arrow :class="{ 'rotate-180': expanded }" />
              </div>
            </template>
            <template #content>
              <profile-menu
                :balance="balance"
                :days-remaining="daysRemaining"
                :limit-remaining="limitRemaining"
                :rate="rate"
                :replenish="replenish"
                @logout="$emit('logout')"
              />
            </template>
          </a-dropdown>
          <div
            v-show="!isAuthenticated && showLogIn"
            class="hidden cursor-pointer items-center gap-2 font-semibold lg:flex"
            @click="goAuth"
          >
            <icon-logout class="lg:h-4 lg:w-4" />
            <span class="hidden lg:inline-block">
              {{ t('header.login') }}
            </span>
          </div>
        </div>
      </div>
    </header>
  </div>
</template>

<style scoped></style>
