import {__} from "@wordpress/i18n";
import MainHeading from "../../../components/MainHeading";
import Description from "../../../components/Description";
import {Table, Td, Th, Tr} from "../../../components/Table";
import Label from "../../../components/Label";
import {Button} from "@wordpress/components";
import Element from "../components/Element";
import useSettingsStore from "../stores/useSettingsStore";
import type {SupportedFieldsProps} from "../types/SupportedFieldsProps";
import localizeSettings from "../types/localizeSettings";

const supportedFields: SupportedFieldsProps[] = localizeSettings.supportedFields;

const FormElements = () => {

	const fields = useSettingsStore(state => state.fields);

	function handleAll(val: boolean) {
		const data = Object
			.entries(fields)
			.reduce((acc, [key]) => ({
				...acc,
				[key]: val
			}), {});
		useSettingsStore.setState({fields: data});
	}

	function handleEnableAll(e: any) {
		e.preventDefault();
		handleAll(true);
	}

	function handleDisableAll(e: any) {
		e.preventDefault();
		handleAll(false);
	}

	return (
		<div className={'hulk-settings-content'}>
			<MainHeading className={'mb-4'}>
				{__('Form Elements', 'advanced-fields-for-elementor-forms')}
			</MainHeading>
			<Table className={'mb-0'}>
				<Tr>
					<Th>
						<Label>{__('Global Control', 'advanced-fields-for-elementor-forms')}</Label>
						<Description>
							{__('Use this to activate or deactivate all form elements at once.')}
						</Description>
					</Th>
					<Td>
						<div className="flex gap-4 mb-4">
							<Button
								type={'button'}
								size={'compact'}
								variant={'primary'}
								onClick={handleEnableAll}
							>
								{__('Enable All', 'advanced-fields-for-elementor-forms')}
							</Button>
							<Button
								type={'button'}
								size={'compact'}
								variant={'secondary'}
								onClick={handleDisableAll}
							>
								{__('Disable All', 'advanced-fields-for-elementor-forms')}
							</Button>
						</div>
						<Description>{__('After enabling or disabling any element make sure to click the Save Changes button.', 'advanced-fields-for-elementor-forms')}</Description>
						<Description>{__('You can disable the elements you are not using on your site. This will disable all associated assets of those elements to improve your site loading speed.', 'advanced-fields-for-elementor-forms')}</Description>
					</Td>
				</Tr>
			</Table>
			<hr/>
			<div className="hulk-elements">
				{supportedFields.map((item, index) => (
					<Element
						key={`hulk-element-${index}`}
						label={item.label}
						demoLink={item.demoLink}
						docLink={item.docLink}
						isPro={!!item.isPro}
						icon={item.icon}
						status={item.status}
						checked={fields[item.slug]}
						onChange={val => {
							const data = {...fields};
							data[item.slug] = val;
							useSettingsStore.setState({fields: data});
						}}
					/>
				))}
			</div>
		</div>
	);
};

export default FormElements;
