import React from "react";
import Select, { components } from "react-select";

const GroupedSelect = ({
	id,
	label,
	value,
	options,
	setOption,
	isDisabled = false,
	isLoading = false,
	noDefaultOption = false,
}) => {
	const customStyles = {
		control: (base) => ({
			...base,
			minHeight: "42px",
			backgroundColor: "white",
			borderColor: "#D1D5DB",
			"&:hover": {
				borderColor: "#9CA3AF",
			},
		}),
		group: (base) => ({
			...base,
			paddingTop: 0,
			paddingBottom: 0,
		}),
		groupHeading: (base) => ({
			...base,
			color: "#6B7280",
			backgroundColor: "#E5E7EB",
			padding: "8px 12px",
			marginBottom: 0,
			fontSize: "0.875rem",
			fontWeight: 600,
			textTransform: "none",
		}),
		option: (base, state) => ({
			...base,
			backgroundColor: state.isFocused ? "#F3F4F6" : "white",
			color: "#111827",
			padding: "8px 12px",
			"&:active": {
				backgroundColor: "#E5E7EB",
			},
		}),
		input: (base) => ({
			...base,
			color: "#111827",
		}),
		singleValue: (base) => ({
			...base,
			color: "#111827",
		}),
		placeholder: (base) => ({
			...base,
			color: "#6B7280",
		}),
	};

	const GroupHeading = (props) => {
		if (props.data.label === "No Filter") {
			return null;
		}
		return <components.GroupHeading {...props} />;
	};

	const formatGroupLabel = (data) => (
		<div className='font-semibold text-sm text-gray-900'>{data.label}</div>
	);

	const handleChange = (selectedOption) => {
		if (selectedOption) {
			setOption(selectedOption.value, id);
		} else {
			setOption("", id);
		}
	};

	// Find the currently selected option from the flattened options array
	const findSelectedOption = (value, options) => {
		if (!value || !options) return null;
		return options.reduce((acc, group) => {
			if (acc) return acc;
			return group.options.find((option) => option.value === value);
		}, null);
	};

	const selectedOption = findSelectedOption(value, options);

	return (
		<div className='w-full'>
			{label && (
				<label className='block text-sm font-semibold leading-6 text-gray-900 mb-2'>
					{label}
				</label>
			)}
			<Select
				value={selectedOption}
				onChange={handleChange}
				options={options}
				isDisabled={isDisabled}
				isLoading={isLoading}
				styles={customStyles}
				formatGroupLabel={formatGroupLabel}
				className='text-sm'
				placeholder='Select...'
				isClearable={!noDefaultOption}
				components={{ GroupHeading }}
			/>
		</div>
	);
};

export default GroupedSelect;
