import { useIntl } from "react-intl"

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

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

export default function RemoveButton({
  confirmationNumber,
  code,
  title,
  onSuccess,
}: {
  confirmationNumber: string
  code: string
  title?: string
  onSuccess: () => void
}) {
  const lang = useLang()
  const intl = useIntl()
  const removePackage = trpc.booking.removePackage.useMutation()

  return (
    <Dialog
      bodyText={intl.formatMessage({
        id: "Are you sure you want to remove this product?",
      })}
      proceedText={intl.formatMessage({ id: "Remove" })}
      proceedIsPending={removePackage.isPending}
      cancelButtonText={intl.formatMessage({ id: "Cancel" })}
      titleText={`${intl.formatMessage({ id: "Remove" })} ${title}`}
      trigger={
        <Button intent="text" size="small" variant="icon" theme="base">
          <DeleteIcon />
          {intl.formatMessage({ id: "Remove" })}
        </Button>
      }
      proceedOnClick={(close) => {
        removePackage.mutate(
          {
            language: lang,
            confirmationNumber,
            codes: [code],
          },
          {
            onSuccess: (data) => {
              if (!data) {
                throw new Error()
              }

              close()
              onSuccess()
            },
            onError: () => {
              toast.error(intl.formatMessage({ id: "Something went wrong!" }))
            },
          }
        )
      }}
    />
  )
}
