import { useEffect, useState } from 'react'

import { cdnUrls, useLinks } from '../core'
import { Environment, isObject } from '../utils'
import { HeaderLinkData } from './header.types'
import { HeaderAccountSectionData } from './headerAccount.types'

type HeaderLinksTemplates = {
  accountSections?: HeaderAccountSectionData[]
  mainLinks?: HeaderLinkData[]
}

/** Loads templates for Header links and enriches them with urls from LinksContext. */
export function useHeaderLinks(env: Environment) {
  const [templates, setTemplates] = useState<HeaderLinksTemplates>({})
  const [links] = useLinks()

  useEffect(() => {
    loadHeaderlinks()

    async function loadHeaderlinks() {
      try {
        const response = await fetch(`${cdnUrls[env]}/common/data/links/header.json`)
        if (!response.ok) return

        const data = await response.json()

        if (isObject(data)) setTemplates(data)
      } catch {
        console.error('Failed to retrieve header data.')
      }
    }
  }, [env])

  const accountSections: HeaderAccountSectionData[] | undefined = templates.accountSections?.map(section => {
    return { ...section, links: section.links?.map(link => ({ ...link, url: links[link?.id ?? ''] })) }
  })

  const mainLinks: HeaderLinkData[] | undefined = templates.mainLinks?.map(link => ({
    ...link,
    url: links[link?.id ?? ''],
  }))

  return { accountSections, mainLinks }
}
