"use client"

import { useIntl } from "react-intl"

import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"
import { TextLinkButton } from "@scandic-hotels/design-system/TextLinkButton"
import { toast } from "@scandic-hotels/design-system/Toast"
import { trpc } from "@scandic-hotels/trpc/client"

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

export default function ManageEmailPreferencesButton() {
  const intl = useIntl()
  const generatePreferencesLink = trpc.user.generatePreferencesLink.useMutation(
    {
      onSuccess: (preferencesLink) => {
        if (preferencesLink) {
          window.open(preferencesLink, "_blank")
        } else {
          toast.error(
            intl.formatMessage({
              id: "profile.manageEmailPreferences.communicationPreferencesUnavailable",
              defaultMessage:
                "It's not possible to manage your communication preferences right now. Please try again later or contact support if the problem persists.",
            })
          )
        }
      },
      onError: () => {
        toast.error(
          intl.formatMessage({
            id: "profile.manageEmailPreferences.anErrorOccured",
            defaultMessage:
              "An error occurred trying to manage your preferences, please try again later.",
          })
        )
      },
    }
  )

  return (
    <TextLinkButton
      theme="Primary"
      className={styles.managePreferencesButton}
      onClick={() => generatePreferencesLink.mutate()}
      typography="Link/md"
      color="Text/Interactive/Secondary"
    >
      <MaterialIcon icon="arrow_forward" color="CurrentColor" />
      {intl.formatMessage({
        id: "profile.manageEmailPreferences",
        defaultMessage: "Manage e-mail preferences",
      })}
    </TextLinkButton>
  )
}
