import React from "react";
import { withJsonFormsControlProps } from "@jsonforms/react";
import {
	rankWith,
	isStringControl,
	isNumberControl,
	isBooleanControl,
	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 TextInputControl = (props: RatingControlProps) => {
	const { handleChange, path, schema, uischema } = props;
	let input: React.ReactNode = (
		<TextInput handleChange={handleChange} path={path} schema={schema} />
	);

	if (uischema?.options?.multi === true) {
		input = <MultilineText handleChange={handleChange} path={path} />;
	}

	return (
		<InputFieldContainer controlProps={props}>{input}</InputFieldContainer>
	);
};

function TextInput({
	handleChange,
	path,
	schema
}: Pick<RatingControlProps, "handleChange" | "path" | "schema">) {
	let inputType = "text";
	let placeholder = "Type something here...";
	if (schema.type === "number" || schema.format === "integer") {
		inputType = "number";
	} else if (schema.format === "password") {
		inputType = "password";
	} else if (schema.format === "email") {
		inputType = "email";
		placeholder = "you@example.com";
	}

	const handleInputChange = (path: string, newValue: string) => {
		if (inputType === "number") {
			handleChange(path, Number(newValue));
		} else {
			handleChange(path, newValue);
		}
	};

	return (
		<input
			type={inputType}
			onChange={(event) => handleInputChange(path, event.target.value)}
			name={path}
			placeholder={placeholder}
			className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
		/>
	);
}

function MultilineText({
	handleChange,
	path
}: Pick<RatingControlProps, "handleChange" | "path">) {
	return (
		<textarea
			rows={4}
			name="comment"
			id="comment"
			className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
			defaultValue={""}
			onChange={(event) => handleChange(path, event.target.value)}
		/>
	);
}

export const numberControlTester: RankedTester = rankWith(3, isNumberControl);

export const textControlTester: RankedTester = rankWith(
	3, //increase rank as needed
	isStringControl
);

export default withJsonFormsControlProps(TextInputControl);
