import {startTransition, useCallback, useEffect, useMemo, useRef, useState} from 'react';
import renderHtmlAttributes from "../../utils/renderHtmlAttributes";
import useFormSubmitSuccess from "../../hooks/useFormSubmitSuccess";
import Pickr from "@simonwep/pickr";
import DropperIcon from "./DropperIcon";
import {__} from "@wordpress/i18n";
import type {FreemiusProps} from "../../types/freemius";
import UpgradeOverlay from "../../components/UpgradeOverlay";

type FieldProps = {
	itemId: string
	formId: string
	attrs: Record<string, string | string[]>
	theme: 'nano' | 'monolith' | 'classic'
	value: string
	format: Pickr.Representation
	valueFormat: Pickr.Representation
	opacity: boolean
	hue: boolean
	palette: boolean
	clear: boolean
	clearText: string
	input: boolean
	hex: boolean
	rgba: boolean
	hsla: boolean
	pickColorText: string
	showSwatches: boolean
	closeOnSelect: boolean
	swatches: string[]
} & FreemiusProps

const Field = (props: FieldProps) => {

	const inputRef = useRef<HTMLInputElement>(null);
	const instance = useRef<Pickr | null>(null);
	const attrs = useMemo(() => renderHtmlAttributes(props.attrs), [props.attrs]);

	const [value, setValue] = useState(props.value);

	// Reset after form submit
	useFormSubmitSuccess(inputRef, () => {
		setValue(props.value);
		instance.current?.setColor(props.value, true);
		instance.current?.hide();
	}, [props.value]);

	const updateInputValue = useCallback((val: Pickr.HSVaColor) => {
		startTransition(() => {
			switch (props.valueFormat) {
				case "CMYK":
					setValue(val.toCMYK().toString(0));
					break;
				case "HSLA":
					setValue(val.toHSLA().toString(0));
					break;
				case "HSVA":
					setValue(val.toHSVA().toString(0));
					break;
				case "RGBA":
					setValue(val.toRGBA().toString(0));
					break;
				default:
					setValue(val.toHEXA().toString(0));
			}
		});
	}, [props.valueFormat]);

	useEffect(() => {
		const element = inputRef.current as HTMLInputElement;
		instance.current = Pickr.create({
			el: element,
			container: '.elementor-form',
			theme: props.theme,
			appClass: 'hulk-ffef-colorpicker-modal',
			useAsButton: true,
			default: props.value || '#42445a',
			defaultRepresentation: props.format,
			...((props.showSwatches && props.swatches.length > 0) && {
				swatches: props.swatches,
			}),
			components: {
				palette: props.palette,
				preview: (props.opacity || props.hue), // Display comparison between previous state and new color
				opacity: props.opacity, // Display opacity slider
				hue: props.hue,     // Display hue slider
				interaction: {
					hex: props.hex,  // Display 'input/output format as hex' button  (hexadecimal representation of the rgba value)
					rgba: props.rgba, // Display 'input/output format as rgba' button (red green blue and alpha)
					hsla: props.hsla, // Display 'input/output format as hsla' button (hue saturation lightness and alpha)
					hsva: false, // Display 'input/output format as hsva' button (hue saturation value and alpha)
					cmyk: false, // Display 'input/output format as cmyk' button (cyan mangenta yellow key )
					input: props.input, // Display input/output textbox which shows the selected color value.
					cancel: false, // Display Cancel Button, resets the color to the previous state
					clear: props.clear, // Display Clear Button; same as cancel, but keeps the window open
					save: false,  // Display Save Button,
				}
			},
			i18n: {
				'btn:clear': props.clearText?.trim() || __('Clear', 'advanced-fields-for-elementor-forms'),
			}
		});
		const pickr = instance.current;
		pickr.on('clear', () => {
			setValue('');
			instance.current?.hide();
		});
		pickr.on('change', (val: any) => {
			updateInputValue(val);
		});
		pickr.on('swatchselect', () => {
			if (props.closeOnSelect) {
				instance.current?.hide();
			}
		});
		return () => {
			pickr?.destroyAndRemove();
		}
	}, [props.clear, props.clearText, props.closeOnSelect, props.format, props.hex, props.hsla, props.hue, props.input, props.opacity, props.palette, props.rgba, props.showSwatches, props.swatches, props.theme, props.value, updateInputValue]);

	function handleClick() {
		instance.current?.show();
	}

	const placeholder = useMemo(() => {
		return props.pickColorText?.trim() || __('Pick Color', 'advanced-fields-for-elementor-forms');
	}, [props.pickColorText]);

	return (
		<>
			{!props.freemius.can_use_premium_code && <UpgradeOverlay url={props.freemius.get_upgrade_url}/>}
			<div className={'hulk-pickcolor-wrap'}>
				<label htmlFor={`${attrs.id}-${props.formId}`} className={'hulk-pickcolor'}>
					<span className="hulk-picker-code" style={{background: value}}>
						{!value && (
							<span className="hulk-picker-empty"><DropperIcon/></span>
						)}
					</span>
					<span className="hulk-pickcolor-text">
						{value || placeholder}
					</span>
				</label>
				<input
					ref={inputRef}
					type="text"
					{...attrs}
					id={`${attrs.id}-${props.formId}`}
					defaultValue={value}
					onClick={handleClick}
					size={1}
				/>
			</div>
			{/* For validation message */}
			<div id={attrs.id}/>
		</>
	);
};

export default Field;
