import { homeHrefs } from "@/constants/homeHrefs"
import { languages } from "@/constants/languages"
import { env } from "@/env/server"
import { batchRequest } from "@/lib/graphql/batchRequest"
import { GetHeader } from "@/lib/graphql/Query/Header.graphql"
import {
  GetDaDeEnUrls,
  GetFiNoSvUrls,
} from "@/lib/graphql/Query/LanguageSwitcher.graphql"
import { request } from "@/lib/graphql/request"

import MainMenu from "./MainMenu"
import OfflineBanner from "./OfflineBanner"
import TopMenu from "./TopMenu"

import styles from "./header.module.css"

import type { HeaderProps } from "@/types/components/current/header"
import { LangParams } from "@/types/params"
import type { HeaderQueryData } from "@/types/requests/header"
import type { LanguageSwitcherQueryData } from "@/types/requests/languageSwitcher"

export default async function Header({ lang, uid }: LangParams & HeaderProps) {
  try {
    const variables = {
      locale: lang,
      uid,
    }

    const { data } = await request<HeaderQueryData>(
      GetHeader,
      { locale: lang },
      { next: { tags: [`header-${lang}`] } }
    )
    const { data: urls } = await batchRequest<LanguageSwitcherQueryData>([
      {
        document: GetDaDeEnUrls,
        tags: [`DA-DE-EN-${uid}`],
        variables,
      },
      {
        document: GetFiNoSvUrls,
        tags: [`FI-NO-SV-${uid}`],
        variables,
      },
    ])

    if (!data.all_header.items.length) {
      return null
    }

    const currentLanguage = languages[lang]
    const homeHref = homeHrefs[env.NODE_ENV][lang]
    const { frontpage_link_text, logoConnection, menu, top_menu } =
      data.all_header.items[0]
    const logo = logoConnection.edges?.[0]?.node
    const topMenuMobileLinks = top_menu.links
      .filter((link) => link.show_on_mobile)
      .sort((a, b) => (a.sort_order_mobile < b.sort_order_mobile ? 1 : -1))

    return (
      <header className={styles.header} role="banner">
        <OfflineBanner />
        <TopMenu
          currentLanguage={currentLanguage}
          frontpageLinkText={frontpage_link_text}
          homeHref={homeHref}
          links={top_menu.links}
          urls={urls}
        />
        <MainMenu
          currentLanguage={currentLanguage}
          frontpageLinkText={frontpage_link_text}
          homeHref={homeHref}
          links={menu.links}
          logo={logo}
          topMenuMobileLinks={topMenuMobileLinks}
          urls={urls}
        />
      </header>
    )
  } catch (error) {
    console.error(error)
    return null
  }
}
