import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import './MyRentals.css';
import { useRentalContext } from './RentalContext';
import rentalsData from '../../src/storage/rentals.json'; // Import rentals data

function MyRentals() {
    const { rentals } = useRentalContext();
    const [rentalsFromJson, setRentalsFromJson] = useState([]);
    const currentUserId = localStorage.getItem('user_id') || null;

    useEffect(() => {
        // Load rentals from JSON
        setRentalsFromJson(rentalsData);
    }, []);

    // Filter rentals from JSON for the current user
    const userRentalsFromJson = rentalsFromJson.filter(rental => rental.userId === currentUserId);

    // Combine rentals from context and JSON
    const combinedRentals = [...rentals.filter(rental => rental.userId === currentUserId), ...userRentalsFromJson];

    if (!currentUserId) {
        return (
            <div className="my-rentals-page">
                <Link to="/" className="back-to-home-button">
                    Back to Home
                </Link>
                <h1>My Rentals</h1>
                <p>Please log in to view your rentals.</p>
            </div>
        );
    }

    return (
        <div className="my-rentals-page">
            <Link to="/" className="back-to-home-button">
                Back to Home
            </Link>
            <h1>My Rentals</h1>
            <div className="rentals-list">
                {combinedRentals.length === 0 ? (
                    <p>No rentals found.</p>
                ) : (
                    combinedRentals.map((rental) => (
                        <div key={rental.id} className="rental-item">
                            <h3>{rental.apartmentName || rental.title}</h3>
                            <p>Name: {rental.name}</p>
                            <p>Check-in: {rental.checkin}</p>
                            <p>Check-out: {rental.checkout}</p>
                            <p>Status: {rental.status}</p>
                        </div>
                    ))
                )}
            </div>
        </div>
    );
}

export default MyRentals;