import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { InspectorControls } from '@wordpress/block-editor';
import { PanelBody, SelectControl, ToggleControl } from '@wordpress/components';
import { useEffect, useState } from '@wordpress/element';
import ServerSideRender from '@wordpress/server-side-render';
import AnimationControls from '../components/animations/AnimationControl';
import AnimatedBlockWrapper from '../components/animations/AnimatedBlockWrapper';
import VisibilityControls from "../components/visibility/VisibilityControls";
import {getVisibilityClasses} from "../components/blockStyleUtils";

const Edit = ({ attributes, setAttributes, name }) => {
	const {
		menu,
		showSearch,
		dropdowns,
		animationEntrance,
		animationDuration,
		animationDelay
	} = attributes;

	const [menuOptions, setMenuOptions] = useState([]);

	useEffect(() => {
		apiFetch({ path: '/wp/v2/menus' })
			.then((res) => {
				if (Array.isArray(res)) {
					setMenuOptions(res.map((m) => ({ label: m.name, value: m.id })));
				}
			})
			.catch((err) => {
				console.error('Failed to load menus:', err);
			});
	}, []);

	return (
		<AnimatedBlockWrapper
			animationEntrance={animationEntrance}
			animationDuration={animationDuration}
			animationDelay={animationDelay}
			attributes={attributes}
			className={`lg-block lg-block__navigation ${getVisibilityClasses(attributes)}`}
		>
			<InspectorControls>
				<PanelBody title={__('Navigation Settings', 'lead-gen')} initialOpen={true}>
					<SelectControl
						label={__('Menu', 'lead-gen')}
						value={menu || null}
						options={[{ label: __('Select a menu', 'lead-gen'), value: '' }, ...menuOptions]}
						onChange={(val) => {
							setAttributes({ menu: val || null });
						}}
					/>
					<ToggleControl
						label={__('Show Search', 'lead-gen')}
						checked={!!showSearch}
						onChange={(val) => setAttributes({ showSearch: val })}
					/>

					<SelectControl
						label={__('Dropdown Style', 'lead-gen')}
						value={dropdowns}
						options={[
							{ label: __('Arrows', 'lead-gen'), value: 'arrows' },
							{ label: __('Plus/Minus', 'lead-gen'), value: 'plus-minus' },
						]}
						onChange={(val) => setAttributes({ dropdowns: val })}
					/>
				</PanelBody>
				<VisibilityControls attributes={attributes} setAttributes={setAttributes} />
				<AnimationControls attributes={attributes} setAttributes={setAttributes} />
			</InspectorControls>

			<ServerSideRender
				block={name}
				attributes={attributes}
			/>
		</AnimatedBlockWrapper>
	);
};

export default Edit;
