import { __ } from '@wordpress/i18n';
import {
	Flex,
	FlexItem,
	PanelBody,
	ToggleControl,
	SelectControl,
	Button,
} from '@wordpress/components';
import {
	InspectorControls,
	RichText,
	PlainText
} from '@wordpress/block-editor';
import { useEffect } from '@wordpress/element';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
	faMinus,
	faPlus,
	faChevronDown
} from '@fortawesome/free-solid-svg-icons';
import AnimationControls from '../components/animations/AnimationControl';
import AnimatedBlockWrapper from '../components/animations/AnimatedBlockWrapper';
import DynamicTag from '../components/DynamicTag';

import { initAccordions } from './script.js';
import VisibilityControls from "../components/visibility/VisibilityControls";
import {getVisibilityClasses} from "../components/blockStyleUtils";

const Edit = ( { attributes, setAttributes, clientId } ) => {
	const {
		accordionItems = [],
		enableToggle = false,
		icon = 'plus_minus',
		titleHtmlTag = 'h2',
		animationEntrance = '',
		animationDuration = '',
		animationDelay = ''
	} = attributes;

	useEffect(() => {
		initAccordions(document);
	}, [accordionItems, icon, enableToggle]);

	const baseId = `accordion_${clientId}`;

	/**
	 * Update a specific accordion item.
	 */
	const updateAccordionItem = ( index, key, value ) => {
		const newItems = [ ...accordionItems ];
		newItems[ index ] = {
			...newItems[ index ],
			[ key ]: value,
		};
		setAttributes( { accordionItems: newItems } );
	};

	/**
	 * Add a new item to the array.
	 */
	const addAccordionItem = () => {
		setAttributes( {
			accordionItems: [
				...accordionItems,
				{ title: '', content: '' }
			]
		} );
	};

	/**
	 * Remove an item by index.
	 */
	const removeAccordionItem = ( index ) => {
		const newItems = [ ...accordionItems ];
		newItems.splice( index, 1 );
		setAttributes( { accordionItems: newItems } );
	};

	const moveAccordionItem = (index, direction) => {
		const newIndex = index + direction;
		if (newIndex < 0 || newIndex >= accordionItems.length) return;

		const newItems = [...accordionItems];
		const [movedItem] = newItems.splice(index, 1);
		newItems.splice(newIndex, 0, movedItem);
		setAttributes({ accordionItems: newItems });
	};

	return (
		<AnimatedBlockWrapper
			animationEntrance={animationEntrance}
			animationDuration={animationDuration}
			animationDelay={animationDelay}
			attributes={attributes}
			className={`lg-block lg-block__accordion ${getVisibilityClasses(attributes)}`}
		>
			<InspectorControls>
				<PanelBody title={__('Accordion Items', 'lead-gen')} initialOpen={true}>
					{accordionItems.map((item, index) => {
						const canMoveUp = index > 0;
						const canMoveDown = index < accordionItems.length - 1;

						return (
							<Flex
								key={index}
								justify="space-between"
								align="center"
								style={{
									marginBottom: '6px',
									padding: '6px',
									border: '1px solid #ddd',
									borderRadius: '4px',
									background: '#fafafa',
								}}
							>
								<FlexItem style={{ flexGrow: 1, fontSize: '13px', fontWeight: 500, flexBasis: '65%', maxWidth: '65%' }}>
									{item.title?.trim() || __('(No title)', 'lead-gen')}
								</FlexItem>

								<FlexItem style={{ display: 'flex', gap: '4px' }}>
									<Button
										icon="arrow-up-alt2"
										label={__('Move Up', 'lead-gen')}
										onClick={() => moveAccordionItem(index, -1)}
										isSmall
										disabled={!canMoveUp}
									/>
									<Button
										icon="arrow-down-alt2"
										label={__('Move Down', 'lead-gen')}
										onClick={() => moveAccordionItem(index, 1)}
										isSmall
										disabled={!canMoveDown}
									/>
									<Button
										icon="trash"
										label={__('Remove item', 'lead-gen')}
										onClick={() => removeAccordionItem(index)}
										isDestructive
										isSmall
									/>
								</FlexItem>
							</Flex>
						);
					})}

					<Button
						variant="primary"
						onClick={addAccordionItem}
						style={{ marginTop: '1em' }}
						icon="plus"
					>
						{__('Add Accordion Item', 'lead-gen')}
					</Button>
				</PanelBody>
				<PanelBody title={ __( 'Accordion Settings', 'lead-gen' ) } initialOpen={ true }>
					<ToggleControl
						label={ __( 'Enable Toggle (Should only one item be open at a time?)', 'lead-gen' ) }
						checked={ enableToggle }
						onChange={ ( val ) => setAttributes( { enableToggle: val } ) }
					/>
					<SelectControl
						label={ __( 'Icon Style', 'lead-gen' ) }
						value={ icon }
						options={ [
							{ label: __( 'Plus/Minus', 'lead-gen' ), value: 'plus_minus' },
							{ label: __( 'Arrows', 'lead-gen' ), value: 'arrows' },
						] }
						onChange={ ( val ) => setAttributes( { icon: val } ) }
					/>
					<SelectControl
						label={ __( 'Title HTML Tag', 'lead-gen' ) }
						value={ titleHtmlTag }
						options={ [
							{ label: 'H1', value: 'h1' },
							{ label: 'H2', value: 'h2' },
							{ label: 'H3', value: 'h3' },
							{ label: 'H4', value: 'h4' },
							{ label: 'H5', value: 'h5' },
							{ label: 'H6', value: 'h6' },
							{ label: 'DIV', value: 'div' },
						] }
						onChange={ ( val ) => setAttributes( { titleHtmlTag: val } ) }
					/>
				</PanelBody>
				<VisibilityControls attributes={attributes} setAttributes={setAttributes} />
				<AnimationControls attributes={attributes} setAttributes={setAttributes} />
			</InspectorControls>

			<div className={ `accordion ${enableToggle ? 'accordion--toggleable' : ''}` }>
				{accordionItems.map((item, index) => {
					const contentId = `${baseId}_content_${index}`;
					const buttonId = `${baseId}_trigger_${index}`;

					return (
						<React.Fragment key={index}>
							<DynamicTag tagName={titleHtmlTag} className="accordion__item">
								<button
									type="button"
									className="accordion__trigger"
									aria-expanded="false"
									aria-controls={contentId}
									id={buttonId}
								>
									<span className="accordion__title">
										<PlainText
											value={item.title}
											onChange={(val) => updateAccordionItem(index, 'title', val)}
											placeholder={__('Add a title', 'lead-gen')}
											className="accordion__title-input"
										/>
									</span>
									<span className="accordion__icon">
									{icon === 'plus_minus' ? (
										<>
											<FontAwesomeIcon icon={faMinus} className="accordion__icon--minus" />
											<FontAwesomeIcon icon={faPlus} className="accordion__icon--plus" />
										</>
										) : (
											<FontAwesomeIcon icon={faChevronDown} className="accordion__icon--arrow" />
										)}
									</span>
								</button>
							</DynamicTag>
							<div
								className="accordion__content"
								id={contentId}
								role="region"
								aria-labelledby={buttonId}
								hidden
							>
								<RichText
									tagName="div"
									className="accordion__content-inner body-font"
									value={item.content}
									onChange={(val) => updateAccordionItem(index, 'content', val)}
									placeholder={__('Add content…', 'lead-gen')}
									allowedFormats={[
										'core/bold',
										'core/italic',
										'core/link',
										'core/underline',
										'core/image',
									]}
								/>
							</div>
						</React.Fragment>
					);
				})}
			</div>
		</AnimatedBlockWrapper>
	);
};

export default Edit;
