import PropTypes from 'prop-types';
import Seat from './Seat';
import styles from './styles.module.css';
import Button from '../../Base/Button/Index';

const BookingWrapper = ({
  selectedSeats,
  seatData,
  currentSeats,
  onSeatAdd,
  onSeatRemove,
  onSeatsConfirm,
  buttonState
}) => {
  const handleSeatClick = (row, seat, status) => {
    if (status == 'current-selected') {
      onSeatRemove(row, seat);
    } else {
      onSeatAdd(row, seat);
    }
  };

  const processedSeatData = seatData?.map((row, rowIndex) =>
    row.map((seat) => {
      if (seat === '*') {
        return { type: 'gap' };
      }

      const foundInCurrentSeats = currentSeats?.find(
        (e) => e.row === rowIndex + 1 && e.seat === seat
      );

      const foundInSelectedSeats = selectedSeats?.some(
        (e) => e.row === rowIndex + 1 && e.seat === seat
      );

      let status = '';
      if (foundInCurrentSeats) status = 'current-selected';
      else if (foundInSelectedSeats) status = 'selected-by-other';

      return {
        seat,
        row: rowIndex + 1,
        status
      };
    })
  );

  return (
    <div className={styles['booking-wrapper']}>
      <div className={styles['theatre']}>
        {processedSeatData?.map((row, rowIndex) => (
          <div key={`row-${rowIndex}`} className={styles['seat-row']}>
            {row.map((seatObj, colIndex) => {
              if (seatObj.type === 'gap') {
                return (
                  <div
                    key={`gap-${rowIndex}-${colIndex}`}
                    className={styles['seat-gap']}
                  />
                );
              }

              const seatKey = `${seatObj.row}-${seatObj.seat}`;

              return (
                <Seat
                  key={seatKey}
                  status={seatObj.status}
                  id={seatObj.seat}
                  onClick={() =>
                    handleSeatClick(seatObj.row, seatObj.seat, seatObj.status)
                  }
                />
              );
            })}
          </div>
        ))}
        <div className={styles['btn-wrapper']}>
          <Button size={'lg'} onClick={onSeatsConfirm} disabled={buttonState}>
            Confirm
          </Button>
        </div>
      </div>
    </div>
  );
};

export default BookingWrapper;

BookingWrapper.propTypes = {
  selectedSeats: PropTypes.arrayOf(
    PropTypes.shape({
      row: PropTypes.number,
      seat: PropTypes.number
    })
  ),
  seatData: PropTypes.arrayOf(
    PropTypes.arrayOf(
      PropTypes.oneOfType([PropTypes.number, PropTypes.oneOf(['*'])])
    )
  ).isRequired,
  currentSeats: PropTypes.arrayOf(
    PropTypes.shape({
      row: PropTypes.number,
      seat: PropTypes.number
    })
  ),
  onSeatAdd: PropTypes.func.isRequired,
  onSeatRemove: PropTypes.func.isRequired,
  onSeatsConfirm: PropTypes.func.isRequired,
  buttonState: PropTypes.bool.isRequired
};
