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 useLang from "@/hooks/useLang"

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

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

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