import { useEffect, useState, useContext } from 'react';
import CascadeSelect from './inputs/CascadeSelect';
import StepTracker from './StepTracker';
import { progressTrackerContext } from '../context/progressTrackerContext';
import NextButton from './navigation/NextButton';
import BackButton from './navigation/BackButton';

const CategoryDropdown = () => {

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

	const [schedule, setSchedule] = useState(null);

	const [selectedOptions, setSelectedOptions] = useState({
		categories: [],
		services: []
	});

	/*
	 * Load the selected schedule.
	 */
	useEffect(() => {

		const storedSchedule =
			sessionStorage.getItem('selectedSchedule');

		if (!storedSchedule) {
			return;
		}

		try {

			const parsedSchedule =
				JSON.parse(storedSchedule);

			setSchedule(parsedSchedule);

			/*
			 * Restore previously selected options
			 * if the user comes back from Step 3.
			 */
			const storedAppointment =
				JSON.parse(
					sessionStorage.getItem(
						'userAppointment'
					)
				);

			if (storedAppointment) {

				setSelectedOptions({

					categories:
						Array.isArray(
							storedAppointment.categories
						)
							? storedAppointment.categories
							: [],

					services:
						Array.isArray(
							storedAppointment.services
						)
							? storedAppointment.services
							: []

				});

			}

		} catch (error) {

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

		}

	}, []);

	/*
	 * Handle category/service checkbox changes.
	 */
	const handleCheckboxChange = (
		taxonomy,
		term,
		checked
	) => {

		setSelectedOptions(prev => {

			const currentTerms =
				prev[taxonomy] || [];

			const updatedTerms = checked

				? [
					...currentTerms,
					term
				]

				: currentTerms.filter(
					id => id !== term
				);

			const updated = {
				...prev,
				[taxonomy]: updatedTerms
			};

			/*
			 * Save current user selections.
			 */
			sessionStorage.setItem(
				'userAppointment',
				JSON.stringify(updated)
			);

			return updated;

		});
	};

	/*
	 * Check whether the user selected
	 * at least one category OR service.
	 */
	const hasSelection =
		selectedOptions.categories.length > 0 ||
		selectedOptions.services.length > 0;

	/*
	 * Next is disabled when there is
	 * no user selection.
	 */
	const disableNext = !hasSelection;

	const handleNext = () => {

		if (disableNext) {
			return;
		}

		setCurrentStep(
			currentStep + 1
		);
	};

	/*
	 * No schedule selected.
	 */
	if (!schedule) {

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

				<p className="booking-api-error">
					Please select a schedule first.
				</p>

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

					<BackButton
						styles="booking-nav-back"
						onClick={() =>
							setCurrentStep(
								currentStep - 1
							)
						}
					/>

				</div>

			</div>
		);

	}

	return (

		<div className="inner-booking-block">

			<p className="booking-component-title">
				Select a Category below
			</p>

			<StepTracker />

			<form
				className="booking-component-wrapper"
				onSubmit={(event) =>
					event.preventDefault()
				}
			>

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

					<CascadeSelect
						dropdownHeading="Select the Categories"
						arrayList={
							schedule.categories || []
						}
						TaxonomyName="categories"
						onChange={
							handleCheckboxChange
						}
						selectedTerms={
							selectedOptions.categories
						}
					/>

					<CascadeSelect
						dropdownHeading="Select the Services"
						arrayList={
							schedule.services || []
						}
						TaxonomyName="services"
						onChange={
							handleCheckboxChange
						}
						selectedTerms={
							selectedOptions.services
						}
					/>

				</div>

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

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

					<BackButton
						styles="booking-nav-back"
						onClick={() =>
							setCurrentStep(
								currentStep - 1
							)
						}
					/>

				</div>

			</form>

		</div>
	);
};

export default CategoryDropdown;