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 './SeatsData.js';

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

export const SeatLayout = ({
  selectedSeats: initialSelected = [],
  reservedSeats = [],
  currentReservedSeats = [],
  limit,
  onSelectionChange,
}) => {
  const [localSelectedSeats, setLocalSelectedSeats] = useState(currentReservedSeats);

  useEffect(() => {
    setLocalSelectedSeats(currentReservedSeats);
  }, [currentReservedSeats]);

  useEffect(() => {
    onSelectionChange?.(localSelectedSeats);
  }, [localSelectedSeats, onSelectionChange]);

  const seatClickHandler = (seat) => {
    const { seatNo, status } = seat;
    if (status === 'reserved') return;

    const hasExisting = currentReservedSeats.length > 0;
    const maxLimit = hasExisting ? Infinity : Number(limit);

    setLocalSelectedSeats((prev) => {
      if (prev.includes(seatNo)) {
        return prev.filter((s) => s !== seatNo);
      } else if (prev.length < maxLimit) {
        return [...prev, seatNo];
      }
      return prev;
    });
  };

  const renderedSeats = populateSeatsArray(
    localSelectedSeats,
    reservedSeats,
    currentReservedSeats
  );

  return (
    <div className={styles.container}>
      {renderedSeats.map((row, i) => (
        <div key={i} className={styles.seatcontainer}>
          {row.map((seat, j) => (
            <Seat key={j} {...seat} onClick={() => seatClickHandler(seat)} />
          ))}
        </div>
      ))}
    </div>
  );
};

SeatLayout.propTypes = {
  selectedSeats: PropTypes.arrayOf(PropTypes.string),
  reservedSeats: PropTypes.arrayOf(PropTypes.string),
  currentReservedSeats: PropTypes.arrayOf(PropTypes.string),
  limit: PropTypes.number.isRequired,
  onSelectionChange: PropTypes.func.isRequired,
};
