"use client"
import { useIntl } from "react-intl"

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

import Dialog from "@/components/Dialog"
import { DeleteIcon } from "@/components/Icons"
import { toast } from "@/components/TempDesignSystem/Toasts"

import type { DeleteCreditCardConfirmationProps } from "@/types/components/myPages/myProfile/creditCards"

export default function DeleteCreditCardConfirmation({
  card,
}: DeleteCreditCardConfirmationProps) {
  const intl = useIntl()
  const trpcUtils = trpc.useUtils()

  const deleteCard = trpc.user.creditCard.delete.useMutation({
    onSuccess() {
      trpcUtils.user.creditCards.invalidate()

      toast.success(
        intl.formatMessage({ id: "Your card was successfully removed!" })
      )
    },
    onError() {
      toast.error(
        intl.formatMessage({
          id: "Something went wrong and we couldn't remove your card. Please try again later.",
        })
      )
    },
  })

  function handleProceedDeleteCard(close: () => void) {
    deleteCard.mutate({ creditCardId: card.id }, { onSettled: close })
  }

  const lastFourDigits = card.truncatedNumber.slice(-4)

  const bodyText = intl.formatMessage(
    {
      id: "Are you sure you want to remove the card ending with {lastFourDigits} from your member profile?",
    },
    { lastFourDigits }
  )

  return (
    <Dialog
      bodyText={bodyText}
      cancelButtonText={intl.formatMessage({ id: "No, keep card" })}
      proceedOnClick={handleProceedDeleteCard}
      proceedText={intl.formatMessage({ id: "Yes, remove my card" })}
      titleText={intl.formatMessage({ id: "Remove card from member profile" })}
      triggerButtonText={<DeleteIcon color="burgundy" />}
    />
  )
}
