import React, { useState } from "react";
import ControlLabel from "./ControlLabel";
import ErrorLabel from "./ErrorLabel";

const DEFAULT_SPACING = 10;
const DEFAULT_COLOR = "#4F46E5";

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

type TFieldWrapperProps = {
	children: React.ReactNode;
	controlProps: ControlProps;
};

export const InputFieldContainer = ({
	controlProps,
	children
}: TFieldWrapperProps) => {
	const { rootSchema, uischema, required, errors } = controlProps;
	const settingsConfig = rootSchema?.settings;
	const verticalSpacing = settingsConfig?.spacing?.vertical ?? DEFAULT_SPACING;
	const horizontalSpacing =
		settingsConfig?.spacing?.horizontal ?? DEFAULT_SPACING;
	return (
		<div
			style={{
				marginTop: verticalSpacing,
				marginBottom: verticalSpacing,
				marginLeft: horizontalSpacing,
				marginRight: horizontalSpacing
			}}>
			<ControlLabel uischema={uischema} required={required} />
			{children}
			<ErrorLabel error={errors} />
		</div>
	);
};

///// WORK IN PROGRESS

// Infer the props of the wrapped component, which should be a kind of input element
type InputComponentProps = React.ComponentPropsWithoutRef<"input">;
export const withCustomInputWrapper = (
	WrappedComponent: React.ComponentType<InputComponentProps>
) => {
	// This component takes the same props as the wrapped component
	return (props: InputComponentProps) => {
		const [isFocused, setIsFocused] = useState(false);

		const handleFocus = () => {
			setIsFocused(true);
		};

		const handleBlur = () => {
			setIsFocused(false);
		};

		const style = isFocused ? {} : {};

		// Pass through all props to the wrapped component, and add the onFocus, onBlur handlers and style
		return (
			<WrappedComponent
				{...props}
				style={style}
				onFocus={handleFocus}
				onBlur={handleBlur}
			/>
		);
	};
};

const InputWithRedBorderOnFocus = withCustomInputWrapper(
	(props: InputComponentProps) => <input {...props} />
);
