import { __ } from '@wordpress/i18n';
import {
	InspectorControls,
	MediaReplaceFlow,
	RichText,
	LinkControl
} from '@wordpress/block-editor';
import {
	PanelBody,
	ToolbarGroup,
	ToolbarButton,
	Button,
	__experimentalToggleGroupControl as ToggleGroupControl,
	__experimentalToggleGroupControlOption as ToggleGroupControlOption,
	Flex,
	FlexItem
} from '@wordpress/components';
import {
	IconPicker,
	InlineIconPicker,
	Image,
} from '@10up/block-components';
import { useState, useEffect } from '@wordpress/element';
import AnimationControls from '../components/animations/AnimationControl';
import AnimatedBlockWrapper from '../components/animations/AnimatedBlockWrapper';
import { registerFontAwesomeIcons } from '../components/icons/registerFontAwesome';
import VisibilityControls from "../components/visibility/VisibilityControls";
import {getVisibilityClasses} from "../components/blockStyleUtils";

const Edit = ({ attributes, setAttributes, clientId }) => {
	const {
		layout,
		list,
		animationEntrance,
		animationDuration,
		animationDelay,
	} = attributes;

	useEffect(() => {
		registerFontAwesomeIcons();
	}, []);

	const [selectedItemIndex, setSelectedItemIndex] = useState(null);

	const updateListItem = (index, updatedItem) => {
		const updatedList = [...list];
		updatedList[index] = { ...updatedList[index], ...updatedItem };
		setAttributes({ list: updatedList });
	};

	const DEFAULT_ICON = {
		type: 'library',
		mediaId: 0,
		url: '',
		library: 'star',
		iconSet: 'fontawesome/solid',
		title: 'Star'
	};

	const addItem = () => {
		setAttributes({
			list: [
				...list,
				{
					icon: DEFAULT_ICON,
					content: '',
					link: {
						url: ''
					}
				}
			]
		});
	};

	const removeItem = (index) => {
		const updated = [...list];
		updated.splice(index, 1);
		setAttributes({ list: updated });
		if (selectedItemIndex === index) {
			setSelectedItemIndex(null);
		} else if (selectedItemIndex > index) {
			setSelectedItemIndex(selectedItemIndex - 1);
		}
	};

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

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

	const handleTypeChange = (index, newType) => {
		updateListItem(index, {
			icon: {
				...DEFAULT_ICON,
				type: newType,
			},
		});
	};

	const handleLibraryIconSelect = (index, iconData) => {
		updateListItem(index, {
			icon: {
				type: 'library',
				mediaId: null,
				url: '',
				library: iconData.name || '',
				iconSet: iconData.iconSet,
			}
		});
	};

	const handleImageSelect = (index, image) => {
		updateListItem(index, {
			icon: {
				type: 'upload',
				mediaId: image.id,
				url: image.url || image.source_url,
				library: '',
				iconSet: '',
				title: image.title || '',
			}
		});
	};

	const handleRemoveUpload = (index) => {
		updateListItem(index, { icon: DEFAULT_ICON });
	};

	const handleLinkChange = (newLink) => {
		if (selectedItemIndex !== null) {
			updateListItem(selectedItemIndex, {
				link: {
					...list[selectedItemIndex].link,
					...newLink,
					opensInNewTab: newLink.opensInNewTab ?? false,
				}
			});
		}
	};

	return (
		<AnimatedBlockWrapper
			animationEntrance={animationEntrance}
			animationDuration={animationDuration}
			animationDelay={animationDelay}
			attributes={attributes}
			className={`lg-block lg-block__icon-list ${getVisibilityClasses(attributes)}`}
		>
			<InspectorControls>
				<PanelBody title={__('List Layout', 'lead-gen')} initialOpen={true}>
					<ToggleGroupControl
						label={__('Layout', 'lead-gen')}
						value={layout}
						isBlock
						onChange={(value) => setAttributes({ layout: value })}
					>
						<ToggleGroupControlOption value="vertical" label="Vertical" />
						<ToggleGroupControlOption value="horizontal" label="Horizontal" />
					</ToggleGroupControl>
				</PanelBody>

				<PanelBody title={__('List Items', 'lead-gen')} initialOpen={true}>
					{list.map((item, index) => {
						const canMoveUp = index > 0;
						const canMoveDown = index < list.length - 1;

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

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

					<Button
						variant="primary"
						onClick={addItem}
						style={{ marginTop: '1em' }}
						icon="plus"
					>
						{__('Add List Item', 'lead-gen')}
					</Button>
				</PanelBody>

				{selectedItemIndex !== null && list[selectedItemIndex] && (
					<>
						<PanelBody
							title={__('Edit Selected Item', 'lead-gen')}
							initialOpen={true}
						>
							<ToggleGroupControl
								label={__('Icon Type', 'lead-gen')}
								value={list[selectedItemIndex].icon.type}
								isBlock
								onChange={(value) => handleTypeChange(selectedItemIndex, value)}
							>
								<ToggleGroupControlOption value="none" label="None" />
								<ToggleGroupControlOption value="upload" label="Upload" />
								<ToggleGroupControlOption value="library" label="Library" />
							</ToggleGroupControl>

							{list[selectedItemIndex].icon.type === 'upload' && list[selectedItemIndex].icon.mediaId ?
								<ToolbarGroup>
									<MediaReplaceFlow
										mediaId={list[selectedItemIndex].icon.mediaId}
										onSelect={(image) => handleImageSelect(selectedItemIndex, image)}
										allowedTypes={['image/svg+xml']}
										accept="image/svg+xml"
									/>
									<ToolbarButton
										onClick={() => handleRemoveUpload(selectedItemIndex)}
										icon="trash"
										label={__('Remove Icon', 'lead-gen')}
									/>
								</ToolbarGroup>
							: null}

							{list[selectedItemIndex].icon.type === 'upload' && (
								<Image
									id={list[selectedItemIndex].icon.mediaId || null}
									size="full"
									onSelect={(image) => handleImageSelect(selectedItemIndex, image)}
									allowedTypes={['image/svg+xml']}
									labels={{
										title: 'Select SVG Image',
										instructions: 'Upload or pick an SVG image.',
									}}
								/>
							)}

							{list[selectedItemIndex].icon.type === 'library' && (
								<IconPicker
									value={{
										name: list[selectedItemIndex].icon.library,
										iconSet: list[selectedItemIndex].icon.iconSet
									}}
									onChange={(iconData) => handleLibraryIconSelect(selectedItemIndex, iconData)}
								/>
							)}

							<p style={{ marginTop: '1em' }}><strong>{__('Link:', 'lead-gen')}</strong></p>
							<div className="custom-link-control" style={{ marginTop: '5px' }}>
								<LinkControl
									value={list[selectedItemIndex].link || { url: '' }}
									onChange={handleLinkChange}
								/>
								{list[selectedItemIndex].link && (
									<Button
										variant="link"
										onClick={() => {
											const updatedList = [ ...list ];
											updatedList[selectedItemIndex] = {
												...updatedList[selectedItemIndex],
												link: null,
											};
											setAttributes({ list: updatedList });
										}}
										isDestructive
										style={{ marginTop: '8px' }}
									>
										Remove Link
									</Button>
								)}
							</div>
						</PanelBody>
					</>
				)}

				<VisibilityControls attributes={attributes} setAttributes={setAttributes} />
				<AnimationControls attributes={attributes} setAttributes={setAttributes} />
			</InspectorControls>

			<ul className={`icon-list icon-list--${layout}`}>
				{list.map((item, index) => {
					const listItemContent = (
						<>
							<div
								className="icon-list__item-icon"
								onClick={() => setSelectedItemIndex(index)}
								style={{ cursor: 'pointer' }}
							>
								{item.icon.type === 'upload' && item.icon.url && (
									<span className="icon-list__icon">
										<img src={item.icon.url} alt="" style={{ width: '1em', height: '1em' }} />
									</span>
								)}
								{item.icon.type === 'library' && item.icon.library && item.icon.iconSet && (
									<span className="icon-list__icon">
										<InlineIconPicker value={{ name: item.icon.library, iconSet: item.icon.iconSet }} onChange={(val) => handleLibraryIconSelect(val)} />
									</span>
								)}
							</div>

							<div className="icon-list__item-text">
								<RichText
									tagName="span"
									value={item.content}
									allowedFormats={ [ 'core/bold', 'core/italic', 'core/strikethrough' ] }
									onChange={(value) => updateListItem(index, { content: value })}
									placeholder={__('List text...', 'lead-gen')}
									className="body-font"
								/>
							</div>
						</>
					);

					return (
						<li
						key={index}
						className="icon-list__item"
						onClick={(e) => {
							if (selectedItemIndex !== index) {
								setSelectedItemIndex(index);
							}
						}}>
							{item.link && item.link.url ? (
								<a
									href={item.link.url}
									className="icon-list__link"
									onClick={(e) => {
										e.preventDefault();
										if (selectedItemIndex !== index) {
											setSelectedItemIndex(index);
										}
										return false;
									}}
									target={item.link.opensInNewTab ? '_blank' : undefined}
									rel={item.link.opensInNewTab ? 'noopener noreferrer' : undefined}
								>
									{listItemContent}
								</a>
							) : (
								listItemContent
							)}
						</li>
					);
				})}
			</ul>
		</AnimatedBlockWrapper>
	);
};

export default Edit;
