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

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

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

import Dialog from "@/components/Dialog"
import Button from "@/components/TempDesignSystem/Button"
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({
          defaultMessage: "Your card was successfully removed!",
        })
      )
    },
    onError() {
      toast.error(
        intl.formatMessage({
          defaultMessage:
            "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(
    {
      defaultMessage:
        "Are you sure you want to remove the card ending with {lastFourDigits} from your member profile?",
    },
    { lastFourDigits }
  )

  return (
    <Dialog
      bodyText={bodyText}
      cancelButtonText={intl.formatMessage({
        defaultMessage: "No, keep card",
      })}
      proceedOnClick={handleProceedDeleteCard}
      proceedText={intl.formatMessage({
        defaultMessage: "Yes, remove my card",
      })}
      titleText={intl.formatMessage({
        defaultMessage: "Remove card from member profile",
      })}
      trigger={
        <Button intent="secondary" size="small" theme="base">
          <MaterialIcon icon="delete" color="Icon/Interactive/Default" />
        </Button>
      }
    />
  )
}
