import React, { useState, useEffect, useRef } from 'react';
import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls, BlockControls } from '@wordpress/block-editor';
import { ToolbarGroup, ToolbarButton, TabPanel, TextControl, Popover } from '@wordpress/components';
import ButtonLayoutTab from '../settings/icon-button/ButtonLayoutTab';
import ButtonStyleTab from '../settings/icon-button/ButtonStyleTab';
import { generateButtonClasses } from '../utilities/generate-button-classes';
import { generateButtonStyles } from '../utilities/generate-button-styles';
import { useCopyPasteButtonStyles } from '../utilities/copy-paste-button-styles';
import { CopyIcon, PasteIcon, LinkIcon, DefaultIcon } from '../components/constants/Icons';
import CustomButton from '../components/CustomButton';
import IconPicker from '../components/IconPicker';
import { isValidUrl } from '../utilities/general-utils';

// Helper function to generate a random unique class name
const generateUniqueClass = () => `ssmb-button-${Math.random().toString( 36 ).substring( 2, 8 )}`;

// Helper function to generate CSS style string
const generateStyleString = ( stylesObject ) => {
	let styles = '';
	for ( const [ key, value ] of Object.entries( stylesObject ) ) {
		styles += `${key}: ${value};`;
	}
	return styles;
};

export default function Edit( { attributes, setAttributes, clientId } ) {
	const { copyStyles, pasteStyles, isPasteEnabled } = useCopyPasteButtonStyles( attributes, setAttributes, clientId );
	const [ isHovered, setIsHovered ] = useState( false );
	const { buttonIcon, buttonIconLink, linkRel, openInNewTab, linkTitle } = attributes;

	const [isLinkInputVisible, setLinkInputVisible] = useState( false );
	const [linkInputValue, setLinkInputValue] = useState( buttonIconLink );
	const [isValidLink, setIsValidLink] = useState( true ); // State for URL validation
	const [isIconPickerVisible, setIsIconPickerVisible] = useState( false ); // State for Icon Picker visibility
	const toolbarButtonRef = useRef( null );
	const iconButtonRef = useRef( null ); // Ref for the icon button

	// Generate button classes and styles
	const { blockButtonClasses, buttonIconClasses, buttonClasses } = generateButtonClasses( attributes );
	const { blockButtonStyles, buttonOverlayStyles, buttonStyles } = generateButtonStyles( {
		...attributes,
		isHovered,
	} );

	useEffect( () => {
		// Generate a new unique class name if none exists or if the current class name is duplicated
		if ( !attributes.uniqueBlockButtonClass || attributes.uniqueBlockButtonClass.startsWith( 'ssmb-button-' ) ) {
			const newClass = generateUniqueClass();
			if ( attributes.uniqueBlockButtonClass !== newClass ) {
				setAttributes( { uniqueBlockButtonClass: newClass } );
			}
		}
	}, [clientId] ); // Depend on clientId to ensure it runs on duplication

	// Handle hover state toggle
	const handleHoverClick = ( hoverState ) => {
		setIsHovered( hoverState );
	};

	// Handle link changes
	const handleUrlChange = ( url ) => {
		const isValid = isValidUrl( url );
		setIsValidLink( isValid );
		setLinkInputValue( url );
	};

	// Validate URL, fallback to '#' if not valid
	const validLink = buttonIconLink && isValidUrl( buttonIconLink ) ? buttonIconLink : '#';

	// Security: rel should include noopener if open in new tab
	const relAttr = linkRel ? `${linkRel} noopener` : 'noopener';

	// Define target attribute based on new tab
	const targetAttr = openInNewTab ? '_blank' : '_self';

	// Handle pressing Enter or clicking the "Enter" button
	const applyLink = () => {
		if ( isValidLink ) {
			setAttributes( { buttonIconLink: linkInputValue } );
			setLinkInputVisible( false ); // Hide the input after applying the link
		}
	};

	const handleKeyDown = ( event ) => {
		if ( event.key === 'Enter' ) {
			applyLink();
		}
	};

	// To update the toolbar state
	useEffect( () => {
		setLinkInputValue( buttonIconLink || '' );
	}, [ buttonIconLink ] );

	// Handle icon selection from the icon picker
	const handleIconSelect = ( icon ) => {
		setAttributes( {
			buttonIcon: {
				iconName: icon.iconName,
				prefix: icon.prefix,
				svg: icon.svg || '',
			},
			isFontAwesome: !!icon.iconName, // Set to true if a FontAwesome icon is selected
		} );
		setIsIconPickerVisible( false ); // Close the icon picker after selecting
	};

	// Define the handleClear function to reset the icon attributes
	const handleClear = () => {
		setAttributes( {
			buttonIcon: { iconName: '', prefix: '', svg: '' }, // Reset icon
			isFontAwesome: false, // Reset FontAwesome flag
		} );
	};

	// Determine whether the icon is cleared (no icon)
	const isIconCleared = !buttonIcon.iconName && !buttonIcon.prefix && !buttonIcon.svg;

	// Generate the style string
	const blockButtonStyleString = generateStyleString( blockButtonStyles );
	const buttonOverlayStyleString = generateStyleString( buttonOverlayStyles );
	const buttonStyleString = generateStyleString( buttonStyles );

	// Block properties for the main div (ssmb-block-button)
	const blockProps = useBlockProps( { className: `${blockButtonClasses} ${isHovered ? 'is-hovered-state' : ''}`, } );

	return (
		<div {...blockProps}>
			{/* Block Controls for Copy and Paste Styles */}
			<BlockControls>
				<ToolbarGroup>
					<ToolbarButton
						icon = { <CopyIcon /> }
						label = { __( 'Copy Button Styles', 'smart-social-media-buttons' ) }
						onClick = { copyStyles }
					/>
					<ToolbarButton
						icon = { <PasteIcon /> }
						label = { __( 'Paste Button Styles', 'smart-social-media-buttons' ) }
						onClick = { pasteStyles }
						disabled = { !isPasteEnabled() } // Disable paste if on the same block
					/>
					<ToolbarButton
						icon = { <LinkIcon /> }
						className = { buttonIconLink ? '' : 'ssmb-disabled-icon' }
						label = { __( 'Add Link', 'smart-social-media-buttons' ) }
						onClick = { () => setLinkInputVisible( true ) }
						ref = { toolbarButtonRef } // Attach the ToolbarButton reference
					/>
					{/* Button for opening the icon picker */}
					<ToolbarButton
						icon = { <DefaultIcon />}
						className = { isIconCleared ? 'ssmb-disabled-icon' : '' }
						label = { __( 'Select Icon', 'smart-social-media-buttons' ) }
						onClick = { () => setIsIconPickerVisible( true ) } // Open icon picker
						ref = { iconButtonRef } // Attach reference for popover
					/>
				</ToolbarGroup>

				{/* Render the Popover for Link Input */}
				{isLinkInputVisible && (
					<Popover
						position = "bottom center"
						onClose = { () => setLinkInputVisible( false ) } // Close the popover when clicking outside
						anchor = { toolbarButtonRef.current }
						className="ssmb-url-input-popover" // Add custom class here
					>
						<div className="ssmb-url-input-wrapper">
							<TextControl
								value = { linkInputValue }
								onChange = { handleUrlChange }
								onKeyDown = { handleKeyDown } // Listen for "Enter" key press
								label = { __( 'Button Link', 'smart-social-media-buttons' ) }
								placeholder = { __( 'Enter a URL', 'smart-social-media-buttons' ) }
								help = { !isValidLink && __( 'Please enter a valid URL (e.g., https://example.com) or #anchor.', 'smart-social-media-buttons' ) } // Show help message if the link is invalid
								__nextHasNoMarginBottom = { true }
							/>
							<button onClick = { applyLink } className="ssmb-apply-link-button">Enter</button>
						</div>
					</Popover>
				)}

				{/* Render the Popover for Icon Picker */}
				{isIconPickerVisible && (
					<Popover
						position = "bottom center"
						onClose = { () => setIsIconPickerVisible( false ) }
						anchor = { iconButtonRef.current }
						className="ssmb-icon-picker-popover"
					>
						<IconPicker onSelectIcon = { handleIconSelect } handleClear = { handleClear } setAttributes = { setAttributes } />
					</Popover>
				)}
			</BlockControls>

			<InspectorControls>
				<TabPanel
					className="ssmb-panel-tabs"
					activeClass="active-tab"
					tabs = { [
						{ name: 'layout', title: __( 'Layout', 'smart-social-media-buttons' ), className: 'layout-tab', },
						{ name: 'style', title: __( 'Style', 'smart-social-media-buttons' ), className: 'style-tab', },
					] }
				>
					{ ( tab ) => {
						if ( tab.name === 'layout' ) {
							return <ButtonLayoutTab attributes = { attributes } setAttributes = { setAttributes } />;
						}

						if ( tab.name === 'style' ) {
							return <ButtonStyleTab attributes = { attributes } setAttributes = { setAttributes } isHovered = { isHovered } handleHoverClick = { handleHoverClick } />
						}

						return null;
					}}
				</TabPanel>
			</InspectorControls>

			{/* Inject the generated style string */}
			<style>{`.ssmb-block-button.${attributes.uniqueBlockButtonClass} { ${blockButtonStyleString} }`}</style>
			<style>{`.ssmb-button-overlay-background.${attributes.uniqueBlockButtonClass}-button-overlay-background { ${buttonOverlayStyleString} }`}</style>
			<style>{`.ssmb-icon-button.${attributes.uniqueBlockButtonClass} { ${buttonStyleString} }`}</style>

			{/* Background overlay (when an image exists) */}
			{ ( attributes.blockButtonBackgroundImageDesktop || attributes.blockButtonBackgroundImageTablet || attributes.blockButtonBackgroundImageMobile
                || attributes.blockButtonBackgroundImageURLDesktop || attributes.blockButtonBackgroundImageURLTablet || attributes.blockButtonBackgroundImageURLMobile
			) && ( <div className={`ssmb-button-overlay-background ${attributes.uniqueBlockButtonClass}-button-overlay-background`}></div> ) }

			{/* Button Wrapper */}
			<div className={ buttonIconClasses }>

				{/* Button Inner styles */}
				<div className={ `${buttonClasses} ${isHovered ? 'is-hovered-state' : ''}`}>

					{/* Render Custom Button */}
					{buttonIconLink ? (
						<a
							href = { validLink }
							target = { targetAttr }
							rel = { relAttr || undefined }
							title = { linkTitle || undefined }
							onClick = { ( e ) => {
								// Disable link click in the editor
								if ( wp.data.select( 'core/editor' ) ) {
									e.preventDefault();
								}
							} }
						>
							<CustomButton
								icon = { buttonIcon }
								buttonIconColor = { attributes.buttonIconColor }
								hoverButtonIconColor = { attributes.hoverButtonIconColor }
								defaultColor = "#ffffff" // Set this to the default color
								isHovered = { isHovered }
							/>
						</a>
					) : (
						<CustomButton
							icon = { buttonIcon }
							buttonIconColor = { attributes.buttonIconColor }
							hoverButtonIconColor = { attributes.hoverButtonIconColor }
							defaultColor = "#ffffff" // Set this to the default color
							isHovered = { isHovered }
						/>
					) }
				</div>
			</div>
		</div>
	);
}
