"use client"

import { useIntl } from "react-intl"

import { BookingStatusEnum } from "@/constants/booking"

import { ChevronDownIcon } from "@/components/Icons"
import Modal from "@/components/Modal"
import Button from "@/components/TempDesignSystem/Button"

import GuaranteeLateArrival from "../GuaranteeLateArrival"
import { useManageStayStore } from "../stores/manageStayStore"
import CancelStay from "./ActionPanel/Actions/CancelStay"
import ModifyStay from "./ActionPanel/Actions/ModifyStay"
import ActionPanel from "./ActionPanel"

import type { Hotel } from "@/types/hotel"
import type { BookingConfirmation } from "@/types/trpc/routers/booking/confirmation"
import { type CreditCard, type User } from "@/types/user"

interface ManageStayProps {
  booking: BookingConfirmation["booking"]
  hotel: Hotel
  setBookingStatus: (status: BookingStatusEnum) => void
  bookingStatus: string | null
  user: User | null
  savedCreditCards: CreditCard[] | null
  refId: string
}

export default function ManageStay({
  booking,
  hotel,
  setBookingStatus,
  bookingStatus,
  user,
  savedCreditCards,
  refId,
}: ManageStayProps) {
  const intl = useIntl()
  const {
    isOpen,
    activeView,
    actions: { setIsOpen, handleCloseModal, setActiveView },
  } = useManageStayStore()

  const showGuaranteeButton =
    bookingStatus !== BookingStatusEnum.Cancelled && !booking.guaranteeInfo

  function renderContent() {
    switch (activeView) {
      case "cancelStay":
        return (
          <CancelStay
            booking={booking}
            hotel={hotel}
            setBookingStatus={() =>
              setBookingStatus(BookingStatusEnum.Cancelled)
            }
          />
        )
      case "modifyStay":
        return <ModifyStay booking={booking} user={user} />
      case "guaranteeLateArrival":
        return (
          <GuaranteeLateArrival
            booking={booking}
            handleCloseModal={handleCloseModal}
            handleBackToManageStay={() => setActiveView("actionPanel")}
            savedCreditCards={savedCreditCards}
            refId={refId}
          />
        )
      default:
        return (
          <ActionPanel
            booking={booking}
            hotel={hotel}
            bookingStatus={bookingStatus}
            onCancelClick={() => setActiveView("cancelStay")}
            onGuaranteeClick={() => setActiveView("guaranteeLateArrival")}
            showGuaranteeButton={showGuaranteeButton}
          />
        )
    }
  }

  return (
    <>
      <Button variant="icon" fullWidth onClick={() => setIsOpen(true)}>
        {intl.formatMessage({ id: "Manage stay" })}
        <ChevronDownIcon width={24} height={24} color="burgundy" />
      </Button>
      <Modal isOpen={isOpen} onToggle={handleCloseModal} withActions hideHeader>
        {renderContent()}
      </Modal>
    </>
  )
}
