"use client"

import { useEffect } from "react"

import { dt } from "@scandic-hotels/common/dt"
import Modal from "@scandic-hotels/design-system/Modal"

import { useAddAncillaryStore } from "@/stores/my-stay/add-ancillary-flow"

import Form from "./Form"
import { calculateBreakfastData } from "./utils"

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

import type { AddAncillaryFlowModalProps } from "@/types/components/myPages/myStay/ancillaries"

export default function AddAncillaryFlowModal({
  booking,
  packages,
  user,
  savedCreditCards,
}: AddAncillaryFlowModalProps) {
  const {
    isOpen,
    closeModal,
    selectedAncillary,
    setBreakfastData,
    isBreakfast,
  } = useAddAncillaryStore((state) => ({
    selectedAncillary: state.selectedAncillary,
    closeModal: state.closeModal,
    setBreakfastData: state.setBreakfastData,
    isBreakfast: state.isBreakfast,
    isOpen: state.isOpen,
  }))

  useEffect(() => {
    setBreakfastData(
      calculateBreakfastData(
        isBreakfast,
        packages,
        booking.adults,
        booking.childrenAges,
        dt(booking.checkOutDate)
          .startOf("day")
          .diff(dt(booking.checkInDate).startOf("day"), "days")
      )
    )
  }, [
    booking.adults,
    booking.checkInDate,
    booking.checkOutDate,
    booking.childrenAges,
    isBreakfast,
    packages,
    setBreakfastData,
  ])

  return (
    <Modal
      isOpen={isOpen}
      onToggle={closeModal}
      title={selectedAncillary?.title || ""}
      withActions
      contentClassName={styles.modalContent}
      className={styles.modal}
    >
      <Form user={user} savedCreditCards={savedCreditCards} booking={booking} />
    </Modal>
  )
}
