import { useEffect, useState, useContext } from 'react';
import fetchUserData from '../services/fetch-user-data';
import StepTracker from './StepTracker';
import { progressTrackerContext } from '../context/progressTrackerContext';
import NextButton from './navigation/NextButton';
import ListSkeleton from './skeleton/ListSkeleton';

const ScheduleDropdown = () => {

	const {
		currentStep,
		setCurrentStep
	} = useContext(progressTrackerContext);

	const [schedules, setSchedules] = useState([]);
	const [selectedSchedule, setSelectedSchedule] = useState(null);
	const [loading, setLoading] = useState(true);
	const [apiError, setApiError] = useState('');

	useEffect(() => {

		const fetchSchedules = async () => {

			try {

				const data = await fetchUserData(
					'ssas/v1/schedule',
					''
				);

				const fetchedSchedules =
					Array.isArray(data)
						? data
						: [];

				setSchedules(
					fetchedSchedules
				);

				/*
				* Restore previously selected schedule
				* from the fresh API data.
				*/
				const storedSchedule =
					sessionStorage.getItem(
						'selectedSchedule'
					);

				if (storedSchedule) {

					try {

						const parsedSchedule =
							JSON.parse(
								storedSchedule
							);

						const restoredSchedule =
							fetchedSchedules.find(
								schedule =>
									schedule.id ===
									parsedSchedule.id
							);

						setSelectedSchedule(
							restoredSchedule || null
						);

					} catch (error) {

						console.error(
							'Failed to restore selected schedule:',
							error
						);

						sessionStorage.removeItem(
							'selectedSchedule'
						);

					}

				}

			} catch (error) {

				console.error(
					'Failed to fetch schedules:',
					error
				);

				setApiError(
					'Unable to load schedules. Please contact the site administrator.'
				);

			} finally {

				setLoading(false);

			}

		};

		fetchSchedules();

	}, []);

	const handleScheduleChange = (event) => {

		const scheduleId = Number(event.target.value);

		const schedule = schedules.find(
			(item) => item.id === scheduleId
		);

		setSelectedSchedule(schedule || null);

		if (schedule) {

			sessionStorage.setItem(
				'selectedSchedule',
				JSON.stringify(schedule)
			);
		} else {

			sessionStorage.removeItem(
				'selectedSchedule'
			);
		}
	};

	const handleNext = () => {

		if (!selectedSchedule) {
			return;
		}

		setCurrentStep(currentStep + 1);
	};

	return (
		<div className="inner-booking-block schedule-selection-step">

			<p className="booking-component-title">
				Select the Schedule
			</p>
			<StepTracker />
			{apiError && (
				<p className="booking-api-error">
					{apiError}
				</p>
			)}

			{loading ? (

				<ListSkeleton amount="1" />

			) : (

				<>
					<div className="schedule-dropdown-wrapper">

						<select
							className="schedule-dropdown"
							value={selectedSchedule?.id || ''}
							onChange={handleScheduleChange}
						>

							<option value="">
								Select a Schedule
							</option>

							{schedules.map((schedule) => (
								<option
									key={schedule.id}
									value={schedule.id}
								>
									{schedule.title}
								</option>
							))}

						</select>

					</div>

					{selectedSchedule && (

						<div className="selected-schedule-card">

							{selectedSchedule.featured_image && (
								<div className="selected-schedule-image">

									<img
										src={selectedSchedule.featured_image}
										alt={selectedSchedule.title}
									/>

								</div>
							)}

							<div className="selected-schedule-content">

								<h3>
									{selectedSchedule.title}
								</h3>

								{selectedSchedule.organiser_name && (
									<div className="schedule-detail">

										<strong>
											Organizer
										</strong>

										<span>
											{selectedSchedule.organiser_name}
										</span>

									</div>
								)}

								{selectedSchedule.venue && (
									<div className="schedule-detail">

										<strong>
											Venue
										</strong>

										<span>
											{selectedSchedule.venue}
										</span>

									</div>
								)}

								{selectedSchedule.famous_services?.length > 0 && (
									<div className="schedule-detail">

										<strong>
											Famous Service
										</strong>

										<span>
											{selectedSchedule.famous_services
												.map(service => service.name)
												.join(', ')
											}
										</span>

									</div>
								)}

							</div>

						</div>
					)}

					<div className="booking-nav-buttons">

						<NextButton
							styles={`booking-nav-next ${
								!selectedSchedule ? 'disabled' : ''
							}`}
							onClick={handleNext}
							innerText="What’s Next"
						/>

					</div>

				</>
			)}

		</div>
	);
};

export default ScheduleDropdown;
