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

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

import Dialog from "@/components/Dialog"

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: "profile.creditCard.cardRemoved",
          defaultMessage: "Your card was successfully removed!",
        })
      )
    },
    onError() {
      toast.error(
        intl.formatMessage({
          id: "profile.creditCard.cardRemoveFailed",
          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(
    {
      id: "profile.creditCard.confirmRemoveCardBody",
      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({
        id: "profile.creditCard.noKeepCard",
        defaultMessage: "No, keep card",
      })}
      proceedOnClick={handleProceedDeleteCard}
      proceedText={intl.formatMessage({
        id: "profile.creditCard.yesRemoveCard",
        defaultMessage: "Yes, remove my card",
      })}
      titleText={intl.formatMessage({
        id: "profile.creditCard.removeCard",
        defaultMessage: "Remove card from member profile",
      })}
      trigger={
        <IconButton
          variant="Muted"
          emphasis
          aria-label={intl.formatMessage({
            id: "profile.creditCard.deleteCard",
            defaultMessage: "Delete card",
          })}
        >
          <MaterialIcon icon="delete" color="Icon/Interactive/Default" />
        </IconButton>
      }
    />
  )
}
