import { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Seat } from '../Seat/Seat.jsx';
import styles from './SeatLayout.module.css';
import { seatsData } from '../SeatLayout/SeatsData.js';

const populateSeatsArray = (selectedSeats, allReservedSeats) => {
  return seatsData.map(({ row, seats }) =>
    seats.map((number) => {
      const seatNo = row + number;
      if (number === '/') {
        return { seatNo, status: 'none' };
      } else if (selectedSeats.includes(seatNo)) {
        return { seatNo, status: 'selected' };
      } else if (allReservedSeats.includes(seatNo)) {
        return { seatNo, status: 'reserved' };
      } else {
        return { seatNo, status: 'available' };
      }
    })
  );
};

export const SeatLayout = ({
  initialReservedSeats = [],
  allReservedSeats = [],
  limit,
  onSelectionChange,
   onSubmit,
}) => {
  const [selectedSeats, setSelectedSeats] = useState(initialReservedSeats);

  useEffect(() => {
    onSelectionChange?.(selectedSeats);
  }, [selectedSeats, onSelectionChange]);
  
  // useEffect(() => {
  //   setSelectedSeats(initialReservedSeats);
  // }, [initialReservedSeats]);

 const seatClickHandler = (seat) => {
  if (seat.status === 'available' || seat.status === 'selected') {
    setSelectedSeats((prevSelected) => {
      let newSelected;
      let actionType;

      if (prevSelected.includes(seat.seatNo)) {
        newSelected = prevSelected.filter((s) => s !== seat.seatNo);
        actionType = 'unclicked';
      } else if (prevSelected.length < limit) {
        newSelected = [...prevSelected, seat.seatNo];
        actionType = 'clicked';
      } else {
        return prevSelected; 
      }

      onSubmit?.(actionType);
      return newSelected;
    });
  }
};
 



  const renderedSeats = populateSeatsArray(selectedSeats, allReservedSeats);
 console.log(selectedSeats);
  return (
    <div className={styles.container}>
  
        {renderedSeats.map((rowSeats, i) => (
          <div key={i} className={styles.seatcontainer}>
            {rowSeats.map((seat, j) => (
              <Seat key={j} onClick={() => seatClickHandler(seat)} {...seat} />
            ))}
          </div>
        ))}
     
    </div>
  );
};

SeatLayout.propTypes = {
  allReservedSeats: PropTypes.arrayOf(PropTypes.string),
  initialReservedSeats: PropTypes.arrayOf(PropTypes.string),
  limit: PropTypes.number,
  onSelectionChange: PropTypes.func,
};
