"use client";
/* 
  This is the counter item component.
  It contains the following components:
  - CounterItem
*/
import React from "react";

// Define the type interface for the props
interface CounterItemProps {
  guests: number;         // 'guests' should be a number
  setGuest: React.Dispatch<React.SetStateAction<number>>; // 'setGuest' is a state setter function
  maxLimits?: number;
  fetchBookingSummary?: any
  checkInDate?: any
  checkOutDate?: any
}

const CounterItem: React.FC<CounterItemProps> = ({ guests, setGuest, maxLimits = 1, fetchBookingSummary, checkInDate, checkOutDate }) => {

  /**
      * Increments the number of guests by 1.
      * @param e - React mouse event
      * @returns void
      */
  const guestIncrement = (e: any) => {
    e.preventDefault();
    e.stopPropagation();

    const maxLimit = maxLimits;

    if (guests < maxLimit) {
      setGuest(guests + 1);
      const payloadData = {
        checkInDate,
        checkOutDate,
        guests: guests + 1
      }
      fetchBookingSummary(payloadData)
    }
  };

  /**
    * Decrements the number of guests by 1, with a minimum of 1.
    * @param e React.MouseEvent
    * @returns void
    */
  const guestDecrement = (e: any) => {
    e.preventDefault();
    e.stopPropagation();
    if (guests === 1) return
    setGuest(Math.max(1, guests - 1));
    const payloadData = {
      checkInDate,
      checkOutDate,
      guests: guests === 1 ? 1 : guests - 1
    }
    fetchBookingSummary(payloadData)
  }

  return (
    <div className={`bg-bgColor py-[6px] px-[14px] rounded-[12px] sm:rounded-full`}>
      <div
        className={`flex items-center justify-between gap-4 sm:gap-2.5 min-w-[60px] max-w-[60px] sm:min-w-[112px] sm:max-w-[112px] w-full`}
      >
        <span className={`${guests === 1 ? "opacity-50" : "cursor-pointer"} `} onClick={(e) => guestDecrement(e)}>
          <i className={`Icon IconMinus w-[14px] h-[14px] sm:w-[16px] sm:h-[16px] bg-blackColor`}></i>
        </span>
        <span className={`inline-block fs-14 font-fw500`}>
          {guests}
        </span>
        <span className={`${maxLimits === guests ? "opacity-50" : "cursor-pointer"}`} onClick={(e) => guestIncrement(e)}>
          <i className={`Icon IconPlus w-[14px] h-[14px] sm:w-[16px] sm:h-[16px] bg-blackColor`}></i>
        </span>
      </div>
    </div>
  );
};

export default CounterItem;
