"use client"
import { useWatch } from "react-hook-form"
import { useIntl } from "react-intl"

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

import { trpc } from "@/lib/trpc/client"
import { useMyStayStore } from "@/stores/my-stay"

import Modal from "@/components/HotelReservation/MyStay/Modal"
import { toast } from "@/components/TempDesignSystem/Toasts"
import useLang from "@/hooks/useLang"
import { trackCancelStay } from "@/utils/tracking"

import CancelStayPriceContainer from "../CancelStayPriceContainer"

import styles from "./finalConfirmation.module.css"

import type { CancelStayFormValues } from "@/types/components/hotelReservation/myStay/cancelStay"

interface FinalConfirmationProps {
  closeModal: () => void
}

export default function FinalConfirmation({
  closeModal,
}: FinalConfirmationProps) {
  const intl = useIntl()
  const lang = useLang()
  const utils = trpc.useUtils()
  const formRooms = useWatch<CancelStayFormValues>({ name: "rooms" })
  const { bookedRoom, rooms } = useMyStayStore((state) => ({
    bookedRoom: state.bookedRoom,
    rooms: state.rooms,
  }))

  const cancelledStayMsg = intl.formatMessage({
    defaultMessage: "Your stay was cancelled",
  })
  const sorryMsg = intl.formatMessage({
    defaultMessage: "We’re sorry that things didn’t work out.",
  })

  const cancelBookingsMutation = trpc.booking.cancel.useMutation({
    onSuccess(data, variables) {
      for (const confirmationNumber of data) {
        if (confirmationNumber) {
          trackCancelStay(bookedRoom.hotelId, confirmationNumber)
        }
      }
      const allCancellationsWentThrough = data.every((cancelled) => cancelled)
      if (allCancellationsWentThrough) {
        if (data.length === rooms.length) {
          toast.success(
            <div className={styles.toastContainer}>
              <Typography variant="Body/Paragraph/mdBold">
                <span className={styles.textDefault}>{cancelledStayMsg}</span>
              </Typography>
              <Typography variant="Body/Supporting text (caption)/smRegular">
                <span className={styles.textDefault}>{sorryMsg}</span>
              </Typography>
            </div>
          )
        } else {
          const cancelledRooms = rooms.filter((r) =>
            variables.refIds.includes(r.refId)
          )
          for (const cancelledRoom of cancelledRooms) {
            toast.success(
              <div className={styles.toastContainer}>
                <Typography variant="Body/Paragraph/mdBold">
                  <span className={styles.textDefault}>
                    <strong>
                      {intl.formatMessage(
                        { defaultMessage: "{roomName} room was cancelled" },
                        { roomName: cancelledRoom.roomName }
                      )}
                    </strong>
                  </span>
                </Typography>
                <Typography variant="Body/Supporting text (caption)/smRegular">
                  <span className={styles.textDefault}>
                    {intl.formatMessage({
                      defaultMessage:
                        "Your Stay is still active with the other room",
                    })}
                  </span>
                </Typography>
              </div>
            )
          }
        }
      } else {
        toast.warning(
          intl.formatMessage({
            defaultMessage:
              "Some rooms were cancelled successfully, but we encountered issues with others. Please contact customer service for assistance.",
          })
        )
      }

      utils.booking.get.invalidate({
        refId: bookedRoom.refId,
      })
      utils.booking.linkedReservations.invalidate({
        lang,
        refId: bookedRoom.refId,
      })
      closeModal()
    },
    onError() {
      toast.error(
        intl.formatMessage({
          defaultMessage: "Something went wrong. Please try again later.",
        })
      )
    },
  })

  function cancelBooking() {
    if (Array.isArray(formRooms)) {
      const refIdsToCancel = formRooms
        .filter((r) => r.checked)
        .map((r) => r.refId)
      if (refIdsToCancel.length) {
        cancelBookingsMutation.mutate({
          refIds: refIdsToCancel,
          language: lang,
        })
      }
    } else {
      toast.error(
        intl.formatMessage({
          defaultMessage: "Something went wrong. Please try again later.",
        })
      )
    }
  }

  const confirm = intl.formatMessage({
    defaultMessage: "Confirm cancellation",
  })
  const dontCancel = intl.formatMessage({
    defaultMessage: "Don't cancel",
  })
  const text = intl.formatMessage({
    defaultMessage: "Are you sure you want to continue with the cancellation?",
  })
  const title = intl.formatMessage({
    defaultMessage: "Cancel booking",
  })

  return (
    <Modal.Content>
      <Modal.Content.Header handleClose={closeModal} title={title}>
        <Typography variant="Body/Paragraph/mdRegular">
          <p className={styles.textDefault}>{text}</p>
        </Typography>
      </Modal.Content.Header>
      <Modal.Content.Body>
        <CancelStayPriceContainer />
      </Modal.Content.Body>
      <Modal.Content.Footer>
        <Modal.Content.Footer.Secondary onClick={closeModal}>
          {dontCancel}
        </Modal.Content.Footer.Secondary>
        <Modal.Content.Footer.Primary
          disabled={cancelBookingsMutation.isPending}
          onClick={cancelBooking}
        >
          {confirm}
        </Modal.Content.Footer.Primary>
      </Modal.Content.Footer>
    </Modal.Content>
  )
}
