import { useState, useEffect } from "react";
import { Seat } from "../Seat/Seat.jsx";
import styles from "./Styles.module.css";
import { toast, ToastContainer } from "react-toastify";
import { Button } from "../../Form/Button/Button.jsx";
export const SeatSelectionComponent = ({
  reservedSeats = [],
  selectedSeats = [],
  seatLimit,
  onClick,
  seats = [],
}) => {
  const [selectedseats, setSelectedSeats] = useState([...selectedSeats]);

  useEffect(() => {
    setSelectedSeats([...selectedSeats]);
  }, [selectedSeats]);

  const controlSeat = (seat) => {
    if (reservedSeats.includes(seat)) {
      toast.info("You can't select this seat because it already reserved!!");
      return;
    }
    if (!selectedseats.includes(seat) && selectedseats.length < seatLimit) {
      setSelectedSeats([...selectedseats, seat]);
    } else if (selectedseats.includes(seat)) {
      setSelectedSeats(selectedseats.filter((e) => e !== seat));
    } else {
      toast.info(`You can't select more than ${seatLimit} seat(s).`);
    }
  };

  const ConfirmSeat = (e) => {
    e.preventDefault();
    if (selectedseats.length < seatLimit) {
      toast.error(`Please select atleast ${seatLimit} seat(s).`);
    } else {
      console.log("Triggered onChange with:", { seats: selectedseats });
      onClick({
        seats: selectedseats,
        clearSelection: () => setSelectedSeats([]),
      });
    }
  };

  const isSeatDisabled = (seat) =>
    reservedSeats.includes(seat) && !selectedSeats.includes(seat);

  return (
    <div className={styles.container}>
      <div className={styles["seat-container"]}>
        {seats?.map((row, rowIndex) => (
          <div key={rowIndex} className={styles.seat}>
            {row?.map((seatNo, seatIndex) => (
              <div
                key={seatIndex}
                className={seatNo === 0 ? styles["remove"] : ""}
              >
                <Seat
                  seatNo={seatNo}
                  onChange={() => {
                    if (!reservedSeats.includes(seatNo) && seatNo !== 0) {
                      controlSeat(seatNo);
                    }
                  }}
                  status={
                    selectedseats.includes(seatNo)
                      ? "selected"
                      : reservedSeats.includes(seatNo)
                      ? "reserved"
                      : "available"
                  }
                  disabled={isSeatDisabled(seatNo)}
                />
              </div>
            ))}
          </div>
        ))}
        <div className={styles.btn}>
          <Button
            children="Confirm"
            backgroundColor="#fff"
            onClick={ConfirmSeat}
          />
        </div>
      </div>

      <ToastContainer />
    </div>
  );
};

SeatSelectionComponent.defaultProps = {
  seats: [],
  reservedSeats: [],
  selectedSeats: [],
};
