"use client"

import { useIntl } from "react-intl"

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

import Button from "@/components/TempDesignSystem/Button"
import { toast } from "@/components/TempDesignSystem/Toasts"

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

export default function ManagePreferencesButton() {
  const intl = useIntl()
  const generatePreferencesLink = trpc.user.generatePreferencesLink.useMutation(
    {
      onSuccess: (preferencesLink) => {
        if (preferencesLink) {
          window.open(preferencesLink, "_blank")
        } else {
          toast.error(
            intl.formatMessage({
              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({
            defaultMessage:
              "An error occurred trying to manage your preferences, please try again later.",
          })
        )
      },
    }
  )

  return (
    <Button
      className={styles.managePreferencesButton}
      variant="icon"
      theme="base"
      intent="text"
      onClick={() => generatePreferencesLink.mutate()}
      wrapping
    >
      <MaterialIcon icon="arrow_forward" color="CurrentColor" />
      {intl.formatMessage({
        defaultMessage: "Manage preferences",
      })}
    </Button>
  )
}
