import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bookSlot, saveDetails, selectSlot } from '../Action/action'; import { withRouter } from './withRouter'; class Booking extends Component { constructor(props) { super(props); this.state = { selectedSlot: null, name: '', contact: '', errorStmt: '', }; } handleSlotClick = (slot) => { const { bookingCheck, selectedDate } = this.props; const isBooked = bookingCheck.some(b => b.slot === slot && b.date === selectedDate); if (!isBooked) { this.setState({ selectedSlot: slot, errorStmt: '' }); this.props.selectSlot(slot); } }; validate = () => { const { selectedSlot, name, contact } = this.state; if (!selectedSlot) { this.setState({ errorStmt: 'Select your slot!!!' }); return false; } const nameRegex = /^[A-Za-z ]+$/; const phoneRegex = /^[0-9]{10}$/; if (!nameRegex.test(name) || !phoneRegex.test(contact)) { this.setState({ errorStmt: 'Invalid Input!!!' }); return false; } return true; }; handleBook = () => { if (!this.validate()) return; const bookingID = Math.floor(1000 + Math.random() * 9000); const { selectedGame, selectedDate } = this.props; const { selectedSlot, name, contact } = this.state; this.props.bookSlot({ id: bookingID, name, contact, game: selectedGame.name, slot: selectedSlot, date: selectedDate }); this.props.saveDetails({ id: bookingID, name, contact }); alert(`Booking successful! Your ID is ${bookingID}`); this.props.navigate('/'); }; render() { const { selectedGame, selectedDate, bookingCheck } = this.props; const { selectedSlot, name, contact, errorStmt } = this.state; const slots = ['10AM', '11AM', '12PM', '1PM', '2PM', '3PM', '4PM']; const today = new Date().toISOString().split('T')[0]; const tomorrow = new Date(); tomorrow.setDate(new Date().getDate() + 1); const formattedTomorrow = tomorrow.toISOString().split('T')[0]; const renderSlots = () => (
{slots.map(slot => { const isBooked = bookingCheck.some(b => b.slot === slot && b.date === selectedDate); const isSelected = selectedSlot === slot; let color = 'green'; if (isBooked) color = 'red'; else if (isSelected) color = 'blue'; return ( this.handleSlotClick(slot)} >

{slot}

); })}
); return (

{selectedGame.name}

{selectedDate}

{selectedDate === today &&

Booking has been closed. Book your slot for {formattedTomorrow}

} {selectedDate === formattedTomorrow && ( <> {renderSlots()} this.setState({ name: e.target.value })} /> this.setState({ contact: e.target.value })} /> {errorStmt &&

{errorStmt}

} )} {selectedDate > formattedTomorrow &&

Booking is not opened yet

}
); } } const mapStateToProps = (state) => ({ selectedGame: state.selectedGame[0] || {}, selectedDate: state.selectedDate, bookingCheck: state.bookingCheck, }); const mapDispatchToProps = { bookSlot, saveDetails, selectSlot, }; export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Booking));