"use client"

import { useRouter } from "next/navigation"
import { useIntl } from "react-intl"

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

import { Loading } from "@/components/Loading"
import Link from "@/components/TempDesignSystem/Link"
import { toast } from "@/components/TempDesignSystem/Toasts"

export function UnlinkSAS() {
  const intl = useIntl()
  const router = useRouter()

  const { mutate, isPending } = trpc.partner.sas.unlinkAccount.useMutation({
    onSuccess() {
      toast.success(intl.formatMessage({ id: "Account unlinked, reloading" }))
      // TODO: reload page
      router.push("/en/scandic-friends/my-pages")
    },
    onError() {
      toast.error(intl.formatMessage({ id: "Failed to unlink account" }))
    },
  })

  const handleClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
    event.preventDefault()
    mutate()
  }

  if (isPending) {
    return <Loading color="burgundy" />
  }

  return (
    <Link
      href="#"
      onClick={handleClick}
      color="burgundy"
      variant="default"
      weight="bold"
    >
      {intl.formatMessage({ id: "Unlink accounts" })}
    </Link>
  )
}
