import React, { useState, useEffect } from 'react';
import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls, useInnerBlocksProps, BlockControls } from '@wordpress/block-editor';
import { ToolbarGroup, ToolbarButton, TabPanel } from '@wordpress/components';
import LayoutTab from './settings/container/ContainerLayoutTab';
import StyleTab from './settings/container/ContainerStyleTab';
import { generateBlockClasses } from './utilities/generate-block-classes';
import { generateBlockStyles } from './utilities/generate-block-styles';
import { useCopyPasteBlockStyles } from './utilities/copy-paste-block-styles';
import { CopyIcon, PasteIcon } from './components/constants/Icons';
import './editor.scss';

// Helper function to generate CSS style string
const generateBlockStyleString = ( 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 } = useCopyPasteBlockStyles( attributes, setAttributes, clientId );
	const [isHovered, setIsHovered] = useState( false );

	// Generate unique class if it doesn't exist
	useEffect( () => {
		if ( !attributes.uniqueClass ) {
			const generatedClass = `ssmb-block-${clientId.substring( 0, 6 )}`;
			setAttributes( { uniqueClass: generatedClass } );
		}
	}, [clientId] );

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

	// Define the template for buttons (if any)
	const TEMPLATE = [
		['ssmb/icon-button', { buttonIcon: { iconName: 'facebook', prefix: 'fab' }, buttonBackgroundColor: '#0866FF' }],
		['ssmb/icon-button', { buttonIcon: { iconName: 'instagram', prefix: 'fab' }, buttonBackgroundColor: '#e1306c' }],
		['ssmb/icon-button', { buttonIcon: { iconName: 'linkedin', prefix: 'fab' }, buttonBackgroundColor: '#0c66c2' }],
		['ssmb/icon-button', { buttonIcon: { iconName: 'x-twitter', prefix: 'fab' }, buttonBackgroundColor: '#000000' }],
		['ssmb/icon-button', { buttonIcon: { iconName: 'youtube', prefix: 'fab' }, buttonBackgroundColor: '#ff0000'}]
	];

	// Determine orientation based on the alignmentMode
	const isHorizontal = attributes.alignmentMode === 'horizontal';
	const orientation = isHorizontal ? 'horizontal' : 'vertical'; // Set the orientation for the inner blocks

	// Ensure clientId is passed to generateBlockClasses and generateBlockStyles
	const { blockWrapperClasses, buttonGroupWrapperClasses, innerBlockEditorClasses } = generateBlockClasses( {
		...attributes,
		clientId, // Ensure clientId is passed
	} );

	const { blockWrapperStyles, buttonGroupWrapperStyles, innerBlocksStyles, overlayStyles } = generateBlockStyles( {
		...attributes,
		isHovered,
		clientId, // Ensure clientId is passed
	} );

	// Generate the style string
	const blockWrapperStyleString = generateBlockStyleString( blockWrapperStyles );
	const buttonGroupWrapperStyleString = generateBlockStyleString( buttonGroupWrapperStyles );
	const innerBlocksStyleString = generateBlockStyleString( innerBlocksStyles );
	const overlayStyleString = generateBlockStyleString( overlayStyles );

	const blockProps = useBlockProps( { className: `${blockWrapperClasses}` } );

	// Use useInnerBlocksProps to get the properties and combine them with your existing classes and styles
	const innerBlocksProps = useInnerBlocksProps(
		{ className: 'ssmb-button-list', },
		{ allowedBlocks: ['ssmb/icon-button'], // Allow only icon-button blocks
			template: TEMPLATE,
			templateLock: false,
			orientation: orientation,
		}
	);

	return (
		<div {...blockProps} >
			{/* Block Controls for Copy and Paste Styles */}
			<BlockControls>
				<ToolbarGroup>
					<ToolbarButton
						icon = { <CopyIcon /> }
						label = { __( 'Copy Styles', 'smart-social-media-buttons' ) }
						onClick = { copyStyles }
					/>
					<ToolbarButton
						icon = { <PasteIcon /> }
						label = { __( 'Paste Styles', 'smart-social-media-buttons' ) }
						onClick = { pasteStyles }
						disabled = { !isPasteEnabled() } // Disable paste if on the same block
					/>
				</ToolbarGroup>
			</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 <LayoutTab attributes = { attributes } setAttributes = { setAttributes } />;
						}

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

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

			{/* Inject the generated style string */}
			<style>{`.ssmb-block-wrapper.${attributes.uniqueClass} { ${blockWrapperStyleString} }`}</style>
			<style>{`.ssmb-button-group-wrapper.${attributes.uniqueClass}-button-group { ${buttonGroupWrapperStyleString} }`}</style>
			<style>{`.ssmb-block-editor-inner-blocks.${attributes.uniqueClass}-button-list { ${innerBlocksStyleString} }`}</style>
			<style>{`.ssmb-overlay-background.${attributes.uniqueClass}-overlay-background { ${overlayStyleString} }`}</style>

			{/* Block Wrapper */}
			<div className={ `${ blockWrapperClasses } ${ isHovered ? 'is-hovered-state' : '' }` }>

				{/* Button Group Wrapper */}
				<div className={ buttonGroupWrapperClasses }>

					{/* Background overlay (when an image exists) */}
					{ ( attributes.backgroundImageDesktop || attributes.backgroundImageTablet || attributes.backgroundImageMobile
                       || attributes.backgroundImageURLDesktop || attributes.backgroundImageURLTablet || attributes.backgroundImageURLMobile
					) && ( <div className={`ssmb-overlay-background ${attributes.uniqueClass}-overlay-background`}></div> ) }

					{/* Block Editor Inner Blocks */}
					<div className={ innerBlockEditorClasses }>

						{/* Inner Blocks Container */}
						<div { ...innerBlocksProps } />
					</div>
				</div>
			</div>
		</div>
	);
}
