"use client"

import { type IntlShape, useIntl } from "react-intl"

import { AlertTypeEnum } from "@scandic-hotels/common/constants/alert"
import { profileConsent } from "@scandic-hotels/common/constants/routes/myPages"
import { Alert } from "@scandic-hotels/design-system/Alert"

import useLang from "@/hooks/useLang"

import { useProfilingConsentAlert } from "./AlertContext"

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

import type { Lang } from "@scandic-hotels/common/constants/language"

type AlertData = {
  type: AlertTypeEnum.Success | AlertTypeEnum.Alarm
  heading: string
  message?: string
  link?: { url: string; title: string }
}

export default function ProfilingConsentAlert() {
  const { alertType, setAlertType } = useProfilingConsentAlert()
  const intl = useIntl()
  const lang = useLang()

  if (!alertType) return null

  const alert = getAlert(alertType, intl, lang)
  if (!alert) return null

  return (
    <Alert
      variant="inline"
      type={alert.type}
      heading={alert.heading}
      link={alert.link}
      text={alert.message}
      close={() => setAlertType(null)}
      className={styles.alert}
    />
  )
}

function getAlert(
  alertType: AlertTypeEnum,
  intl: IntlShape,
  lang: Lang
): AlertData | null {
  switch (alertType) {
    case AlertTypeEnum.Success:
      return {
        type: AlertTypeEnum.Success,
        heading: intl.formatMessage({
          id: "profilingConsent.alert.preferenceSaved",
          defaultMessage: "Preference saved!",
        }),
        link: {
          url: profileConsent[lang],
          title: intl.formatMessage({
            id: "profilingConsent.alert.editIn",
            defaultMessage: "Edit in Personalization & Profiling",
          }),
        },
      }

    case AlertTypeEnum.Alarm:
      return {
        type: AlertTypeEnum.Alarm,
        heading: intl.formatMessage({
          id: "profilingConsent.alert.preferenceNotSaved",
          defaultMessage: "Preference not saved!",
        }),
        message: intl.formatMessage({
          id: "profilingConsent.alert.anErrorOcurred",
          defaultMessage:
            "An error occurred when updating preferences, please try again later.",
        }),
      }

    default:
      return null
  }
}
