import React, { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import './BookingPage.css';
import apartments from '../../src/storage/apartments.json';
import { useRentalContext } from './RentalContext'; // Import useRentalContext

function BookingPage() {
    const { apartmentId } = useParams();
    const navigate = useNavigate();
    const apartment = apartments.find(apartment => apartment.id === parseInt(apartmentId));
    const [formData, setFormData] = useState({
        name: '',
        email: '',
        checkin: '',
        checkout: ''
    });
    const [message, setMessage] = useState('');
    const [isSuccess, setIsSuccess] = useState(false);
    const { addRental } = useRentalContext(); // Use addRental from RentalContext

    const handleChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();

        const checkinDate = new Date(formData.checkin);
        const checkoutDate = new Date(formData.checkout);
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        if (checkinDate < today) {
            setMessage('Check-in date cannot be in the past.');
            setIsSuccess(false);
            return;
        }

        if (checkoutDate <= checkinDate) {
            setMessage('Check-out date must be after check-in date.');
            setIsSuccess(false);
            return;
        }

        try {
            const userId = localStorage.getItem('user_id');
            if (!userId) {
                setMessage('Please log in to make a booking.');
                setIsSuccess(false);
                return;
            }

            const newRental = {
                id: Date.now(),
                userId: userId,
                apartmentId: apartmentId,
                name: formData.name,
                email: formData.email,
                checkin: formData.checkin,
                checkout: formData.checkout,
                apartmentName: apartment.name, // Include apartment name
                apartmentPrice: apartment.price, // Include apartment price
                status: 'Pending'
            };

            addRental(newRental); // Add the new rental to the context

            setMessage('Booking successful!');
            setIsSuccess(true);
            setFormData({ name: '', email: '', checkin: '', checkout: '' });
        } catch (error) {
            setMessage('Booking failed. Please try again.');
            setIsSuccess(false);
        }
    };

    const handleBackToHome = () => {
        navigate('/');
    };

    if (!apartment) {
        return (
            <div className="booking-page dark-theme">
                <button className="back-to-home-button" onClick={handleBackToHome}>
                    Back to Home
                </button>
                <h1>Apartment Not Found</h1>
                <p>The requested apartment could not be found.</p>
            </div>
        );
    }

    return (
        <div className="booking-page dark-theme">
            <button className="back-to-home-button" onClick={handleBackToHome}>
                Back to Home
            </button>

            <h1>Book Your Apartment Now!</h1>
            <p>Please fill out the form below to complete your booking.</p>

            <form className="booking-form" onSubmit={handleSubmit}>
                <h2 className='name'>{apartment.name}</h2>

                <div className="form-group">
                    <label htmlFor="name">Name:</label>
                    <input type="text" id="name" name="name" required value={formData.name} onChange={handleChange} />
                </div>

                <div className="form-group">
                    <label htmlFor="email">Email:</label>
                    <input type="email" id="email" name="email" required value={formData.email} onChange={handleChange} />
                </div>

                <div className="form-group">
                    <label htmlFor="checkin">Check-in Date:</label>
                    <input type="date" id="checkin" name="checkin" required value={formData.checkin} onChange={handleChange} />
                </div>

                <div className="form-group">
                    <label htmlFor="checkout">Check-out Date:</label>
                    <input type="date" id="checkout" name="checkout" required value={formData.checkout} onChange={handleChange} />
                </div>

                <p className="apartment-price">{apartment.price}</p>

                <button type="submit" className="submit-button">Complete Booking</button>
            </form>

            {message && (
                <div className={`message ${isSuccess ? 'success' : 'error'}`}>
                    {message}
                </div>
            )}
        </div>
    );
}

export default BookingPage;