"use client"

import { useIntl } from "react-intl"

import { trpc } from "@/lib/trpc/client"

import ArrowRight from "@/components/Icons/ArrowRight"
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({
              id: "It is not posible to manage your communication preferences right now, please try again later or contact support if the problem persists.",
            })
          )
        }
      },
      onError: (e) => {
        toast.error(
          intl.formatMessage({
            id: "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
    >
      <ArrowRight color="burgundy" />
      {intl.formatMessage({ id: "Manage preferences" })}
    </Button>
  )
}
