"use client"

import { cx } from "class-variance-authority"
import FocusLock from "react-focus-lock"
import { useIntl } from "react-intl"

import { logout } from "@scandic-hotels/common/constants/routes/handleAuth"
import { Divider } from "@scandic-hotels/design-system/Divider"
import { Typography } from "@scandic-hotels/design-system/Typography"
import { trpc } from "@scandic-hotels/trpc/client"

import useLang from "@/hooks/useLang"

import { MenuLink } from "../MenuLink"

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

import type { MyPagesLinkKey } from "@scandic-hotels/trpc/routers/navigation/mypages/MyPagesLink"

import type { MyPagesMenuProps } from "../MyPagesMenu"

type Props = MyPagesMenuProps & { toggleOpenStateFn: () => void }

export default function MyPagesMenuContent({
  membership,
  toggleOpenStateFn,
  user,
  membershipLevel,
}: Props) {
  const intl = useIntl()
  const { data: myPagesNavigation } = useMyPagesNavigation()

  const primaryLinks = myPagesNavigation?.primaryLinks ?? []
  const secondaryLinks = myPagesNavigation?.secondaryLinks ?? []

  const membershipPoints = membership?.currentPoints
  const showMembershipInfo = membershipLevel && membershipPoints !== undefined

  if (primaryLinks.length === 0 && secondaryLinks.length === 0) {
    return null
  }

  return (
    <FocusLock returnFocus={true}>
      <nav className={styles.myPagesMenuContent}>
        <div
          className={cx(styles.intro, {
            [styles.noMembership]: !showMembershipInfo,
          })}
        >
          <Typography variant="Title/Subtitle/md" className={styles.userName}>
            <p data-hj-suppress>
              {intl.formatMessage(
                {
                  id: "myPages.hiFirstName",
                  defaultMessage: "Hi {firstName}!",
                },
                { firstName: user.firstName }
              )}
            </p>
          </Typography>
          {showMembershipInfo ? (
            <div className={styles.friendTypeWrapper}>
              <Typography variant="Title/Overline/sm">
                <span className={styles.friendType}>
                  {membershipLevel.name}
                </span>
              </Typography>
              <Typography variant="Body/Paragraph/mdRegular">
                <span>
                  {intl.formatMessage(
                    {
                      id: "common.pointsAmountPoints",
                      defaultMessage: "{pointsAmount, number} points",
                    },
                    { pointsAmount: membershipPoints }
                  )}
                </span>
              </Typography>
            </div>
          ) : null}
          <Divider className={styles.divider} />
        </div>

        <PrimaryLinks toggleOpenStateFn={toggleOpenStateFn} />
        <Divider className={styles.divider} />
        <SecondaryLinks toggleOpenStateFn={toggleOpenStateFn} />
      </nav>
    </FocusLock>
  )
}

function PrimaryLinks({
  toggleOpenStateFn,
}: {
  toggleOpenStateFn: () => void
}) {
  const { data: myPagesNavigation } = useMyPagesNavigation()

  const primaryLinks = myPagesNavigation?.primaryLinks ?? []

  return (
    <ul className={styles.menuItems}>
      {primaryLinks.map(({ text, href }) => (
        <li key={`${text}-${href}`}>
          <MenuLink href={href} onClick={toggleOpenStateFn}>
            {text}
          </MenuLink>
        </li>
      ))}
    </ul>
  )
}

function SecondaryLinks({
  toggleOpenStateFn,
}: {
  toggleOpenStateFn: () => void
}) {
  const intl = useIntl()
  const lang = useLang()
  const { data: myPagesNavigation } = useMyPagesNavigation()

  const secondaryLinks = myPagesNavigation?.secondaryLinks ?? []

  return (
    <ul className={styles.menuItems}>
      {secondaryLinks.map(({ text, href }) => (
        <li key={`${text}-${href}`}>
          <MenuLink href={href} onClick={toggleOpenStateFn}>
            {text}
          </MenuLink>
        </li>
      ))}
      <li>
        <MenuLink href={logout[lang]} prefetch={false}>
          {intl.formatMessage({
            id: "common.logOut",
            defaultMessage: "Log out",
          })}
        </MenuLink>
      </li>
    </ul>
  )
}

export const useMyPagesNavigation = () => {
  const lang = useLang()
  const intl = useIntl()

  const MyPagesLinkTranslationMap: Record<MyPagesLinkKey, string> = {
    overview: intl.formatMessage({
      id: "common.overview",
      defaultMessage: "Overview",
    }),
    points: intl.formatMessage({
      id: "common.myPoints",
      defaultMessage: "My points",
    }),
    stays: intl.formatMessage({
      id: "common.myStays",
      defaultMessage: "My stays",
    }),
    benefits: intl.formatMessage({
      id: "common.myBenefits",
      defaultMessage: "My benefits",
    }),
    partnerSas: intl.formatMessage({
      id: "myPagesMenu.partnerSas",
      defaultMessage: "Scandic ♥ SAS",
    }),
    teamMemberCard: intl.formatMessage({
      id: "common.teamMemberCard",
      defaultMessage: "Team Member Card",
    }),
    scandicFriends: intl.formatMessage({
      id: "common.aboutScandicFriends",
      defaultMessage: "About Scandic Friends",
    }),
    profile: intl.formatMessage({
      id: "common.myProfile",
      defaultMessage: "My profile",
    }),
  }

  const result = trpc.navigation.myPages.useQuery({
    lang: lang,
  })

  if (result.data) {
    const primaryLinks = result.data.primaryLinks.map((link) => ({
      ...link,
      text: MyPagesLinkTranslationMap[link.key],
    }))
    const secondaryLinks = result.data.secondaryLinks.map((link) => ({
      ...link,
      text: MyPagesLinkTranslationMap[link.key],
    }))

    return { ...result, data: { primaryLinks, secondaryLinks } }
  }

  return { ...result, data: null }
}
