import React, { useState } from 'react';

const CascadeSelect = ({
	dropdownHeading,
	arrayList,
	TaxonomyName,
	onChange,
	selectedTerms = []
}) => {

	const [openDropdown, setOpenDropdown] = useState(false);

	const handleToggle = () => {
		setOpenDropdown(prev => !prev);
	};

	const handleCheckboxChange = (e, term) => {

		const checked = e.target.checked;

		onChange(
			TaxonomyName,
			term,
			checked
		);
	};

	return (
		<div className="categories-dropdown">

			<p
				onClick={handleToggle}
				className={`booking-dropdown-heading ${
					openDropdown
						? 'open-dropdown-heading'
						: ''
				}`}
			>
				{dropdownHeading}
			</p>

			<div
				className={`dropdown-options ${
					openDropdown
						? 'dropdown-open'
						: ''
				}`}
			>

				{arrayList.length > 0 ? (

					arrayList.map((term) => (

						<label key={term.id}>

							{term.name}

							<input
								type="checkbox"
								value={term.id}
								onChange={(e) =>
									handleCheckboxChange(
										e,
										term.id
									)
								}
								checked={
									selectedTerms.includes(
										term.id
									)
								}
							/>

							<span></span>

						</label>

					))

				) : (

					<p>
						No {TaxonomyName} Found!
					</p>

				)}

			</div>

		</div>
	);
};

export default CascadeSelect;