import { firaMono, firaSans } from "@/app/[lang]/(live)/fonts"

import Header from "@/components/MyPages/Header"
import Sidebar from "@/components/MyPages/Sidebar"

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

import type { LangParams, LayoutArgs } from "@/types/params"
import { request } from "@/lib/graphql/request"
import {
  GetNavigationMyPagesData,
  NavigationItem,
  MenuItem,
  PageLink,
  PageLinkEnum,
} from "@/types/requests/myPages/navigation"
import { GetNavigationMyPages } from "@/lib/graphql/Query/NavigationMyPages.graphql"

function getURL(node: PageLink) {
  switch (node.__typename) {
    case PageLinkEnum.ContentPage:
      return node.web.url
    case PageLinkEnum.AccountPage:
    case PageLinkEnum.LoyaltyPage:
    case PageLinkEnum.CodeDefinedPage:
      return node.url
  }
}

function mapMenuItems(navigationItems: NavigationItem[]) {
  return navigationItems.map(({ item }): MenuItem => {
    const { node } = item.pageConnection.edges[0]
    const {
      title,
      system: { uid },
    } = node

    return {
      title,
      uid,
      url: getURL(node),
      linkText: item.link_text,
      subItems: item.sub_items ? mapMenuItems(item.sub_items) : null,
    }
  })
}

export default async function MyPagesLayout({
  children,
  params,
}: React.PropsWithChildren<LayoutArgs<LangParams>>) {
  const response = await request<GetNavigationMyPagesData>(
    GetNavigationMyPages,
    {
      locale: params.lang,
    }
  )
  // navigation_my_pages is of type Single, hence the hard [0]
  const navigation = response.data.all_navigation_my_pages.items[0]
  const menuItems = mapMenuItems(navigation.items)

  return (
    <div className={`${firaMono.variable} ${firaSans.variable} ${styles.page}`}>
      <Header lang={params.lang} />
      <div className={styles.content}>
        <Sidebar menuItems={menuItems} />
        {children}
      </div>
    </div>
  )
}
