import React from "react";
import { withJsonFormsControlProps } from "@jsonforms/react";
import {
	rankWith,
	isEnumControl,
	isPrimitiveArrayControl,
	RankedTester
} from "@jsonforms/core";
import { InputFieldContainer } from "./InputWrapper";

interface RatingControlProps {
	data: any;
	handleChange(path: string, value: any): void;
	path: string;
	schema: any;
	uischema: any;
	enabled: boolean;
	id: string;
	errors: any;
	required?: boolean;
	rootSchema: any;
}

const SelectInputControl = (props: RatingControlProps) => {
	const { handleChange, path, schema } = props;
	let options = [];
	let isMultiSelect = false;
	if (schema.type === "string") {
		options = schema?.enum ?? [];
	} else if (schema.type === "array") {
		options = schema.items?.enum ?? [];
		isMultiSelect = true;
	}

	const handleSingleSelectChange = (
		event: React.ChangeEvent<HTMLSelectElement>
	) => {
		const newValue = event.target.value;
		handleChange(path, newValue);
	};

	const handleMultiSelectChange = (
		event: React.ChangeEvent<HTMLSelectElement>
	) => {
		const selectedOptions = Array.from(event.target.selectedOptions).map(
			(option) => option.value
		);
		handleChange(path, selectedOptions);
	};

	return (
		<InputFieldContainer controlProps={props}>
			<select
				multiple={isMultiSelect}
				id={path}
				name={path}
				className="mt-2 block w-full rounded-md border-0 py-1.5 pl-3 pr-10 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-indigo-600 sm:text-sm sm:leading-6"
				onChange={
					isMultiSelect ? handleMultiSelectChange : handleSingleSelectChange
				}>
				{options.map((option: any) => (
					<option key={option} value={option}>
						{option}
					</option>
				))}
			</select>
		</InputFieldContainer>
	);
};

export const singleSelectControlTester: RankedTester = rankWith(
	4, //increase rank as needed
	isEnumControl
);

export const multiSelectControlTester: RankedTester = rankWith(
	5, //increase rank as needed
	isPrimitiveArrayControl
);

export default withJsonFormsControlProps(SelectInputControl);
