"use client"

import { useRouter } from "next/navigation"
import { useEffect, useRef } from "react"
import { useIntl } from "react-intl"

import { StickyElementNameEnum } from "@/stores/sticky-position"

import Link from "@/components/TempDesignSystem/Link"
import useHash from "@/hooks/useHash"
import useScrollSpy from "@/hooks/useScrollSpy"
import useStickyPosition from "@/hooks/useStickyPosition"

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

import {
  HotelHashValues,
  type TabNavigationProps,
} from "@/types/components/hotelPage/tabNavigation"

export default function TabNavigation({
  restaurantTitle,
  hasActivities,
  hasFAQ,
}: TabNavigationProps) {
  const hash = useHash()
  const intl = useIntl()
  const router = useRouter()
  const tabNavigationRef = useRef<HTMLDivElement>(null)
  useStickyPosition({
    ref: tabNavigationRef,
    name: StickyElementNameEnum.HOTEL_TAB_NAVIGATION,
    group: "hotelPage",
  })

  const tabLinks: { hash: HotelHashValues; text: string }[] = [
    {
      hash: HotelHashValues.overview,
      text: intl.formatMessage({ id: "Overview" }),
    },
    { hash: HotelHashValues.rooms, text: intl.formatMessage({ id: "Rooms" }) },
    {
      hash: HotelHashValues.restaurant,
      text: intl.formatMessage({ id: restaurantTitle }, { count: 1 }),
    },
    {
      hash: HotelHashValues.meetings,
      text: intl.formatMessage({ id: "Meetings & Conferences" }),
    },
    {
      hash: HotelHashValues.wellness,
      text: intl.formatMessage({ id: "Wellness & Exercise" }),
    },
    ...(hasActivities
      ? [
          {
            hash: HotelHashValues.activities,
            text: intl.formatMessage({ id: "Activities" }),
          },
        ]
      : []),
    ...(hasFAQ
      ? [
          {
            hash: HotelHashValues.faq,
            text: intl.formatMessage({ id: "FAQ" }),
          },
        ]
      : []),
  ]

  const { activeSectionId, pauseScrollSpy } = useScrollSpy(
    tabLinks.map(({ hash }) => hash)
  )

  useEffect(() => {
    if (activeSectionId) {
      router.replace(`#${activeSectionId}`, { scroll: false })
    }
  }, [activeSectionId, router])

  return (
    <div ref={tabNavigationRef} className={styles.stickyWrapper}>
      <nav className={styles.tabsContainer}>
        {tabLinks.map((link) => {
          const isActive =
            hash === link.hash ||
            (!hash && link.hash === HotelHashValues.overview)
          return (
            <Link
              key={link.hash}
              href={`#${link.hash}`}
              active={isActive}
              variant="tab"
              color="burgundy"
              textDecoration="none"
              scroll={true}
              onClick={pauseScrollSpy}
            >
              {link.text}
            </Link>
          )
        })}
      </nav>
    </div>
  )
}
