import {memo, useState} from 'react';
import {__} from "@wordpress/i18n";
import {Button, Icon, Modal, ToggleControl} from "@wordpress/components";
import {external, page} from "@wordpress/icons";
import type {SupportedFieldsStatus} from "../types/SupportedFieldsProps";
import localizeSettings from "../types/localizeSettings";
import noop from "../../../utils/noop";
import upgradeUrl from "../../../utils/upgradeUrl";

type ElementProps = {
	label: string;
	demoLink: string;
	docLink: string;
	checked: boolean;
	onChange: (val: boolean) => void;
	isPro: boolean
	icon: string
	status?: SupportedFieldsStatus
}

const Element = (props: ElementProps) => {

	const [isOpen, setOpen] = useState(false);
	const openModal = () => setOpen(true);
	const closeModal = () => setOpen(false);

	function handleClick() {
		openModal();
	}

	return (
		<>
			<div
				className="hulk-element-item"
				data-status={props.status}
				{...props.isPro && {
					onClick: handleClick
				}}
				onKeyDown={noop}
				role="button"
				tabIndex={-1}
			>
				{props.isPro && (
					<div className="is-pro">{__('Pro', 'advanced-fields-for-elementor-forms')}</div>
				)}
				<div className="block-title">
					{props.icon && <img src={props.icon} alt={props.label}/>}
					<h4 dangerouslySetInnerHTML={{__html: props.label}}/>
				</div>
				<div className="block-content">
					<a
						href={props.demoLink}
						title={__('Live Demo', 'advanced-fields-for-elementor-forms')}
						target="_blank" rel="noreferrer"
						onClick={event => event.stopPropagation()}
					>
						<Icon icon={external} size={22}/>
					</a>
					<a
						href={props.isPro ? upgradeUrl : props.docLink}
						title={__('Documentation', 'advanced-fields-for-elementor-forms')}
						target="_blank" rel="noreferrer"
						{...props.isPro && {
							onClick: (event) => {
								event.preventDefault();
								event.stopPropagation();
								openModal();
							}
						}}
					>
						<Icon icon={page} size={22}/>
					</a>
					<ToggleControl
						label=""
						checked={props.isPro ? false : props.checked}
						onChange={(val) => {
							if (props.isPro) {
								return;
							}
							props.onChange(val);
						}}
					/>
				</div>
			</div>
			{(props.isPro && isOpen) && (
				<Modal
					className={'hulk-pro-modal'}
					onRequestClose={closeModal}
					size={'medium'}
				>
					<div className="hulk-modal-wrap">
						<div className="hulk-modal-icon">
							<img src={localizeSettings.PLUGIN_DIR_URL + 'assets/icons/modal-icon.svg'}
								 alt={__('Upgrade', 'advanced-fields-for-elementor-forms')}/>
						</div>
						<h4>{__('Upgrade to PRO version to use this field', 'advanced-fields-for-elementor-forms')}</h4>
						<Button
							href={upgradeUrl}
							variant="primary"
						>
							{__('Upgrade to Pro', 'advanced-fields-for-elementor-forms')}
						</Button>
					</div>
				</Modal>
			)}
		</>
	);
};

export default memo(Element);
