"use client"

import { useIntl } from "react-intl"

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

import { useManageStayStore } from "@/stores/my-stay/manageStayStore"
import { useMyStayRoomDetailsStore } from "@/stores/my-stay/myStayRoomDetailsStore"

import Modal from "@/components/Modal"
import Button from "@/components/TempDesignSystem/Button"

import GuaranteeLateArrival from "../GuaranteeLateArrival"
import CancelStay from "./ActionPanel/Actions/CancelStay"
import ModifyStay from "./ActionPanel/Actions/ModifyStay"
import ActionPanel from "./ActionPanel"

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

import type { Hotel } from "@/types/hotel"
import { type CreditCard } from "@/types/user"

interface ManageStayProps {
  hotel: Hotel
  savedCreditCards: CreditCard[] | null
  refId: string
  isLoggedIn: boolean
}

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

  const bookedRoom = useMyStayRoomDetailsStore((state) => state.bookedRoom)
  const linkedReservationRooms = useMyStayRoomDetailsStore(
    (state) => state.linkedReservationRooms
  )

  const allRoomsCancelled =
    linkedReservationRooms.every((room) => room.isCancelled) &&
    bookedRoom.isCancelled

  function renderContent() {
    switch (activeView) {
      case "cancelStay":
        return <CancelStay hotel={hotel} />
      case "modifyStay":
        return <ModifyStay isLoggedIn={isLoggedIn} />
      case "guaranteeLateArrival":
        return (
          <GuaranteeLateArrival
            savedCreditCards={savedCreditCards}
            refId={refId}
          />
        )
      default:
        return <ActionPanel hotel={hotel} />
    }
  }

  return (
    <>
      <Button
        variant="icon"
        fullWidth
        onClick={() => setIsOpen(true)}
        size="small"
        disabled={allRoomsCancelled}
        className={styles.manageStayButton}
      >
        {intl.formatMessage({ id: "Manage stay" })}
        <MaterialIcon
          icon="keyboard_arrow_down"
          color={
            allRoomsCancelled ? "Icon/Interactive/Disabled" : "Icon/Inverted"
          }
        />
      </Button>
      {isOpen && (
        <Modal
          isOpen={isOpen}
          onToggle={handleCloseModal}
          withActions
          hideHeader
        >
          {renderContent()}
        </Modal>
      )}
    </>
  )
}
