import styles from './styles.module.css';
import Seat from './Seat';

const BookingWrapper = ({ onSeatClick, selectedSeats, seatData }) => {

    const aisleIndex = 5;
    const currentUser = 2;


    const selectedSeatMap = new Map();

    selectedSeats?.forEach(user => {
        user.selected.forEach(seat => {
            const key = `${seat.row}-${seat.seat}`;
            selectedSeatMap.set(key, user.userid);
        });
    });


    const isLeftBlock = (col) => col < aisleIndex;
    const isRightBlock = (col) => col > aisleIndex;



    return (
        <div>
            <div className={styles['theatre']}>
                {seatData?.map((row, row_index) => (
                    <div className={styles['seat-row']}>
                        {row.columnData?.map((column, column_index) => {
                            const isFirstRow = row_index === 0;
                            const isLastRow = row_index === seatData.length - 1;

                            if (isLeftBlock(column_index) && column_index === 0 && (isFirstRow || isLastRow)) {
                                return <div key={`gap-left-${row_index}-${column_index}`} className={styles["seat-gap"]} />;
                            }

                            if (
                                isRightBlock(column_index) &&
                                column_index === row.columnData.length - 1 &&
                                (isFirstRow || isLastRow)

                            ) {
                                return <div key={`gap-right-${row_index}-${row_index}`} className={styles["seat-gap"]} />;
                            }

                            if (column_index == aisleIndex) {
                                return (
                                    <div className={styles['aisle']}></div>
                                )
                            }

                            const seatKey = `${row.row_id}-${column.id}`;
                            const selectedBy = selectedSeatMap.get(seatKey);
                            let seatClass = ``;
                            if (selectedBy) {
                                seatClass += selectedBy === currentUser ? 'selected-by-me' : 'selected-by-other';
                            }
                            return (
                                <Seat status={seatClass} id={column.id} onClick={() => onSeatClick(row.row_id, column.id)} />
                            )
                        })}
                    </div>
                ))}
            </div>
        </div>
    )
}

export default BookingWrapper;

