import { useRouter } from "next/navigation"
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"
import { trackRemoveAncillary } from "@/utils/tracking/myStay"

import type { Room } from "@/types/stores/my-stay"
import type { PackageSchema } from "@/types/trpc/routers/booking/confirmation"

export default function RemoveButton({
  refId,
  codes,
  title,
  booking,
  ancillary,
  addedBreakfastPackages,
}: {
  refId: string
  codes: string[]
  title?: string
  booking: Room
  ancillary: PackageSchema
  addedBreakfastPackages: PackageSchema[] | undefined
}) {
  const lang = useLang()
  const intl = useIntl()
  const utils = trpc.useUtils()
  const router = useRouter()

  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()
              }
              utils.booking.get.invalidate({
                refId: refId,
              })
              trackRemoveAncillary(
                ancillary,
                booking.hotelId,
                booking.ancillary?.deliveryTime,
                addedBreakfastPackages
              )
              router.refresh()

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