/*
 * Button Icon Panel
 */

import { __ } from '@wordpress/i18n';
import { useState, useEffect, useRef } from 'react';
import { PanelBody, BaseControl, Popover, Button, ButtonGroup, ColorPalette, RangeControl } from '@wordpress/components';
import { LeftIcon, RightIcon, NormalStateIcon, HoverStateIcon } from '../../../components/constants/Icons';
import DecimalNumberInput from '../../../components/DecimalNumberInput';
import ButtonIconPreview from '../../../components/ButtonIconPreview';
import defaultColors from '../../../components/constants/DefaultColorsPalette';
import IconPicker from '../../../components/IconPicker';
import ResponsiveRangeControl from '../../../responsive-controls/ResponsiveRangeControl';
import { useIconPanelBodyClass } from '../../../components/IconPanelIndicator';
import ResetIconButton from '../../../components/ResetIconButton';

export default function ButtonIconPanel( { attributes, setAttributes, isHovered, handleHoverClick } ) {
	const {
		buttonIcon, buttonIconColor, buttonIconOpacity,
		buttonIconRotation, buttonIconPosition,
		hoverButtonIconColor, hoverButtonIconOpacity, hoverButtonIconRotation,
		buttonIconNoverEffect,
	} = attributes;

	// Use the custom hook to handle the panel class update
	useIconPanelBodyClass( attributes, [
		'buttonIcon', 'buttonIconColor', 'buttonIconOpacity',
		'buttonIconRotation', 'buttonIconPosition',
		'hoverButtonIconColor', 'hoverButtonIconOpacity', 'hoverButtonIconRotation',
		'buttonIconNoverEffect',
		'buttonIconSizeDesktop', 'buttonIconSizeTablet', 'buttonIconSizeMobile',
		'buttonIconGapDesktop', 'buttonIconGapTablet', 'buttonIconGapMobile'
	], 'desktop', __( 'Icon', 'smart-social-media-buttons' ) );

	const resetButtonIcon = () => setAttributes( { buttonIcon: { iconName: 'circle-notch', prefix: 'far' }, isFontAwesome: true } );
	const resetButtonIconColor = () => setAttributes( { buttonIconColor: '#ffffff' } );
	const resetButtonIconOpacity = () => setAttributes( { buttonIconOpacity: 1 } );
	const resetButtonIconRotation = () => setAttributes( { buttonIconRotation: 1 } );
	const resetButtonIconPosition = () => setAttributes( { buttonIconPosition: 'left' } );

	const resetHoverButtonIconColor = () => setAttributes( { hoverButtonIconColor: null } );
	const resetHoverButtonIconOpacity = () => setAttributes( { hoverButtonIconOpacity: 1 } );
	const resetHoverButtonIconRotation = () => setAttributes( { hoverButtonIconRotation: 1 } );

	const [ isPickerOpen, setIsPickerOpen ] = useState( false );
	const iconButtonRef = useRef( null ); // Ref to the button to attach the popover

	const handleIconSelect = ( icon ) => {
		if ( icon ) {
			setAttributes( {
				buttonIcon: {
					iconName: icon.iconName,
					prefix: icon.prefix,
					svg: icon.svg // This will either be SVG content or an empty string
				},
				isFontAwesome: !!icon.iconName // true if it's a FontAwesome icon
			} );
		} else {
			setAttributes( {
				buttonIcon: { iconName: "", prefix: "", svg: "" },
				isFontAwesome: false
			} );
		}
	};

	const handleClear = () => {
		setIsPickerOpen( false );
		setAttributes( {
			buttonIcon: { iconName: "", prefix: "", svg: "" }, // Reset to empty icon
			isFontAwesome: false // Set isFontAwesome to false
		} );
	};

	return (
		<>
			<PanelBody title = { __( 'Icon', 'smart-social-media-buttons' ) } initialOpen = { true }>
				<BaseControl className="ssmb-button-icon" label = { __( 'Icon', 'smart-social-media-buttons' ) } __nextHasNoMarginBottom = { true }>
					<div className="ssmb-control-wrapper">
						<div className="ssmb-button-icon-control">
							<div className="ssmb-button-icon-wrapper">
								<button
									ref = { iconButtonRef }
									type = "button"
									className="components-button ssmb-select-icon-button ssmb-preview-icon"
									onClick = { () => setIsPickerOpen( !isPickerOpen ) } // Toggle popover
								>
									<ButtonIconPreview icon = { buttonIcon } />
								</button>
							</div>
						</div>
						<ResetIconButton
							currentAttributes = { attributes }
							attributeKeys = { ['buttonIcon'] }
							setAttributes = { setAttributes }
							onClick = { resetButtonIcon }
							label = { __( 'Reset Icon', 'smart-social-media-buttons' ) }
							panelTitle = { __( 'Icon', 'smart-social-media-buttons' ) }
							blockType = 'ssmb/icon-button'
						/>
					</div>

					{/* Popover for Icon Picker */}
					{isPickerOpen && (
						<Popover
							onClose = { () => setIsPickerOpen( false ) }
							anchor = { iconButtonRef.current }
							placement = "bottom-start"
							className="ssmb-icon-picker-popover"
						>
							<IconPicker
								onSelectIcon = { handleIconSelect }
								handleClear = { handleClear }
								setAttributes = { setAttributes }
							/>

						</Popover>
					) }
				</BaseControl>

				<>
					<ButtonGroup className="ssmb-toggle-state-controls">
						<Button
							icon = { <NormalStateIcon /> }
							variant = { !isHovered ? 'primary' : 'secondary' }
							onClick = { () => handleHoverClick( false ) }
						>
							{__( 'Normal', 'smart-social-media-buttons' ) }
						</Button>
						<Button
							icon = { <HoverStateIcon /> }
							variant = { isHovered ? 'primary' : 'secondary' }
							onClick = { () => handleHoverClick( true ) }
						>
							{__( 'Hover', 'smart-social-media-buttons' ) }
						</Button>
					</ButtonGroup>

					{ isHovered ? (
						<>
							{/* HOVER MODE */}
							{/* Icon Color */}
							<BaseControl className="ssmb-color-palette-control" label = { __( 'Hover Icon Color', 'smart-social-media-buttons' ) } __nextHasNoMarginBottom = { true }>
								<div className="ssmb-control-wrapper">
									<ColorPalette
										colors = { defaultColors }
										value = { hoverButtonIconColor }
										onChange = { ( newColor ) => setAttributes( { hoverButtonIconColor: newColor } ) }
										clearable
									/>
									<ResetIconButton
										currentAttributes = { attributes }
										attributeKeys = { ['hoverButtonIconColor'] }
										setAttributes = { setAttributes }
										onClick = { resetHoverButtonIconColor }
										label = { __( 'Reset Icon Color', 'smart-social-media-buttons' ) }
										panelTitle = { __( 'Icon', 'smart-social-media-buttons' ) }
										blockType = 'ssmb/icon-button'
									/>
								</div>
							</BaseControl>

							<BaseControl className="ssmb-color-opacity-control" label = { __( 'Hover Icon Color Opacity', 'smart-social-media-buttons' ) } __nextHasNoMarginBottom = { true }>
								<div className="ssmb-control-wrapper">
									<RangeControl
										value = { hoverButtonIconOpacity }
										onChange = { ( newOpacity ) => setAttributes( { hoverButtonIconOpacity: newOpacity } ) }
										min = { 0 }
										max = { 1 }
										step = { 0.01 }
										__nextHasNoMarginBottom = { true }
									/>
									<DecimalNumberInput
										value = { hoverButtonIconOpacity }
										onChange = { ( newOpacity ) => setAttributes( { hoverButtonIconOpacity: newOpacity } ) }
										min = { 0 }
										max = { 1 }
										step = { 0.01 }
										className="ssmb-input-control"
										style = { { width: '64px' } }
									/>
									<ResetIconButton
										currentAttributes = { attributes }
										attributeKeys = { ['hoverButtonIconOpacity'] }
										setAttributes = { setAttributes }
										onClick = { resetHoverButtonIconOpacity }
										label = { __( 'Reset Icon Color Opacity', 'smart-social-media-buttons' ) }
									/>
								</div>
							</BaseControl>
						</>
					) : (
						<>
							{/* NORMAL MODE */}
							{/* Icon Color */}
							<BaseControl className="ssmb-color-palette-control" label = { __( 'Icon Color', 'smart-social-media-buttons' ) } __nextHasNoMarginBottom = { true }>
								<div className="ssmb-control-wrapper">
									<ColorPalette
										colors = { defaultColors }
										value = { buttonIconColor }
										onChange = { ( newColor ) => setAttributes( { buttonIconColor: newColor } ) }
										clearable
									/>
									<ResetIconButton
										currentAttributes = { attributes }
										attributeKeys = { ['buttonIconColor'] }
										setAttributes = { setAttributes }
										onClick = { resetButtonIconColor }
										label = { __( 'Reset Icon Color', 'smart-social-media-buttons' ) }
										panelTitle = { __( 'Icon', 'smart-social-media-buttons' ) }
										blockType = 'ssmb/icon-button'
									/>
								</div>
							</BaseControl>

							{/* Icon Color Opacity */}
							<BaseControl className="ssmb-color-opacity-control" label = { __( 'Icon Color Opacity', 'smart-social-media-buttons' ) } __nextHasNoMarginBottom = { true }>
								<div className="ssmb-control-wrapper">
									<RangeControl
										value = { buttonIconOpacity }
										onChange = { ( newOpacity ) => setAttributes( { buttonIconOpacity: newOpacity } ) }
										min = { 0 }
										max = { 1 }
										step = { 0.01 }
										__nextHasNoMarginBottom = { true }
									/>
									<DecimalNumberInput
										value = { buttonIconOpacity }
										onChange = { ( newOpacity ) => setAttributes( { buttonIconOpacity: newOpacity } ) }
										min = { 0 }
										max = { 1 }
										step = { 0.01 }
										className="ssmb-input-control"
										style = { { width: '64px' } }
									/>
									<ResetIconButton
										currentAttributes = { attributes }
										attributeKeys = { ['buttonIconOpacity'] }
										setAttributes = { setAttributes }
										onClick = { resetButtonIconOpacity }
										label = { __( 'Reset Icon Color Opacity', 'smart-social-media-buttons' ) }
										panelTitle = { __( 'Icon', 'smart-social-media-buttons' ) }
										blockType = 'ssmb/icon-button'
									/>
								</div>
							</BaseControl>
						</>
					) }
				</>

				{/* Hover Effect */}
				<BaseControl className="ssmb-hover-effect-control" label = { __( 'Hover Effect', 'smart-social-media-buttons' ) } __nextHasNoMarginBottom = { true }>
					<div className="ssmb-control-wrapper">
						<select
							value = { buttonIconNoverEffect }
							onChange = { ( event ) => setAttributes( { buttonIconNoverEffect: event.target.value } ) }
							className="ssmb-select"
						>
							<option value = "none">{ __( 'No Effect', 'smart-social-media-buttons' ) }</option>
							<option value = "hover-scale">{ __( 'Scale', 'smart-social-media-buttons' ) }</option>
							<option value = "hover-lift">{ __( 'Lift', 'smart-social-media-buttons' ) }</option>
							<option value = "hover-lift-scale">{ __( 'Lift & Scale', 'smart-social-media-buttons' ) }</option>
							<option value = "hover-darken">{ __( 'Darken', 'smart-social-media-buttons' ) }</option>
							<option value = "hover-blink">{ __( 'Blink', 'smart-social-media-buttons' ) }</option>
							<option value = "hover-rotate">{ __( 'Rotate', 'smart-social-media-buttons' ) }</option>
							<option value = "hover-skew">{ __( 'Skew', 'smart-social-media-buttons' ) }</option>
							<option value = "hover-invert">{ __( 'Invert', 'smart-social-media-buttons' ) }</option>
							<option value = "hover-blur">{ __( 'Blur', 'smart-social-media-buttons' ) }</option>
						</select>
						<ResetIconButton
							currentAttributes = { attributes }
							attributeKeys = { ['buttonIconNoverEffect'] }
							setAttributes = { setAttributes }
							onClick = { () => setAttributes( { buttonIconNoverEffect: '' } ) } // Reset to 'None'
							label = { __( 'Reset Hover Effect', 'smart-social-media-buttons' ) }
							panelTitle = { __( 'Icon', 'smart-social-media-buttons' ) }
							blockType = 'ssmb/icon-button'
						/>
					</div>
				</BaseControl>

				{/* Icon Size */}
				<ResponsiveRangeControl
					attributes = { attributes }
					setAttributes = { setAttributes }
					label = { __( 'Icon Size', 'smart-social-media-buttons' ) }
					attributeKeys = { {
						desktop: 'buttonIconSizeDesktop',
						tablet: 'buttonIconSizeTablet',
						mobile: 'buttonIconSizeMobile'
					} }
					minValues = { { desktop: 0, tablet: 0, mobile: 0 } }
					maxValues = { { desktop: 100, tablet: 100, mobile: 100 } }
					defaultValue = { 18 }
					ResetComponent = { ResetIconButton }
					panelTitle = { __( 'Icon', 'smart-social-media-buttons' ) }
					blockType = 'ssmb/icon-button'
				/>

				<>
					<ButtonGroup className="ssmb-toggle-state-controls">
						<Button
							icon = { <NormalStateIcon /> }
							variant = {!isHovered ? 'primary' : 'secondary' }
							onClick = { () => handleHoverClick( false ) }
						>
							{__( 'Normal', 'smart-social-media-buttons' ) }
						</Button>
						<Button
							icon = { <HoverStateIcon /> }
							variant = { isHovered ? 'primary' : 'secondary' }
							onClick = { () => handleHoverClick( true ) }
						>
							{__( 'Hover', 'smart-social-media-buttons' ) }
						</Button>
					</ButtonGroup>

					{ isHovered ? (
						<>
							{/* HOVER MODE */}
							{/* Icon Rotation */}
							<BaseControl className="ssmb-rotation-control" label = { __( 'Hover Icon Rotation', 'smart-social-media-buttons' ) } __nextHasNoMarginBottom = { true }>
								<div className="ssmb-control-wrapper">
									<RangeControl
										value = { hoverButtonIconRotation }
										onChange = { ( newValue ) => setAttributes( { hoverButtonIconRotation: newValue } ) }
										min = { 0 }
										max = { 360 }
										__nextHasNoMarginBottom = { true }
									/>
									<input
										type = "number"
										value = { hoverButtonIconRotation }
										onChange = { ( e ) => {
											let inputValue = e.target.value;

											// Remove leading zeros and disallow negative signs
											inputValue = inputValue.replace( /^0+(?!$)/, '' ).replace( /^-/, '' );

											// Parse to integer
											let parsedValue = parseInt( inputValue, 10 );

											// If the parsed value is not a valid number, set it to 0
											if ( isNaN( parsedValue ) ) {
												parsedValue = 0;
											}

											// Clamp the value between 0 and 360
											parsedValue = Math.min( Math.max( parsedValue, 0 ), 360 );

											// Update the input field to show the corrected value
											e.target.value = parsedValue;

											// Update the attribute
											setAttributes( { hoverButtonIconRotation: parsedValue } );
										}}
										min = { 0 }
										max = { 360 }
										className="ssmb-input-control"
										style = { { minWidth: '64px' } }
									/>
									<ResetIconButton
										currentAttributes = { attributes }
										attributeKeys = { ['hoverButtonIconRotation'] }
										setAttributes = { setAttributes }
										onClick = { resetHoverButtonIconRotation }
										label = { __( 'Reset Icon Rotation', 'smart-social-media-buttons' ) }
										panelTitle = { __( 'Icon', 'smart-social-media-buttons' ) }
										blockType = 'ssmb/icon-button'
									/>
								</div>
							</BaseControl>
						</>
					) : (
						<>
							{/* NORMAL MODE */}
							{/* Icon Rotation */}
							<BaseControl className="ssmb-rotation-control" label = { __( 'Icon Rotation', 'smart-social-media-buttons' ) } __nextHasNoMarginBottom = { true }>
								<div className="ssmb-control-wrapper">
									<RangeControl
										value = { buttonIconRotation }
										onChange = { ( newValue ) => setAttributes( { buttonIconRotation: newValue } ) }
										min = { 0 }
										max = { 360 }
										__nextHasNoMarginBottom = { true }
									/>
									<input
										type = "number"
										value = { buttonIconRotation }
										onChange = { ( e ) => {
											let inputValue = e.target.value;

											// Remove leading zeros and disallow negative signs
											inputValue = inputValue.replace( /^0+(?!$)/, '' ).replace( /^-/, '' );

											// Parse to integer
											let parsedValue = parseInt( inputValue, 10 );

											// If the parsed value is not a valid number, set it to 0
											if ( isNaN( parsedValue ) ) {
												parsedValue = 0;
											}

											// Clamp the value between 0 and 360
											parsedValue = Math.min( Math.max( parsedValue, 0 ), 360 );

											// Update the input field to show the corrected value
											e.target.value = parsedValue;

											// Update the attribute
											setAttributes( { buttonIconRotation: parsedValue } );
										}}
										min = { 0 }
										max = { 360 }
										className="ssmb-input-control"
										style = { { minWidth: '64px' } }
									/>
									<ResetIconButton
										currentAttributes = { attributes }
										attributeKeys = { ['buttonIconRotation'] }
										setAttributes = { setAttributes }
										onClick = { resetButtonIconRotation }
										label = { __( 'Reset Icon Rotation', 'smart-social-media-buttons' ) }
										panelTitle = { __( 'Icon', 'smart-social-media-buttons' ) }
										blockType = 'ssmb/icon-button'
									/>
								</div>
							</BaseControl>
						</>
					) }
				</>

				{/* Icon Position */}
				<BaseControl className="ssmb-icon-position" label = { __( 'Icon Position', 'smart-social-media-buttons' ) } __nextHasNoMarginBottom = { true }>
					<div className="ssmb-control-wrapper">
						<ButtonGroup className="ssmb-alignment-controls ssmb-button-content-vertical-alignment" style = { { flexGrow: 1 } }>
							<Button
								className="left"
								icon = { <LeftIcon /> }
								label = { __( 'Left', 'smart-social-media-buttons' ) }
								isPressed = { buttonIconPosition === 'left' }
								onClick = { () => setAttributes( { buttonIconPosition: 'left' } ) }
							/>
							<Button
								className="alignment-right"
								icon = { <RightIcon /> }
								label = { __( 'Right', 'smart-social-media-buttons' ) }
								isPressed = { buttonIconPosition === 'right' }
								onClick = { () => setAttributes( { buttonIconPosition: 'right' } ) }
							/>
						</ButtonGroup>
						<ResetIconButton
							currentAttributes = { attributes }
							attributeKeys = { ['buttonIconPosition'] }
							setAttributes = { setAttributes }
							onClick = { resetButtonIconPosition }
							label = { __( 'Reset Vertical Alignment', 'smart-social-media-buttons' ) }
							panelTitle = { __( 'Icon', 'smart-social-media-buttons' ) }
							blockType = 'ssmb/icon-button'
						/>
					</div>
				</BaseControl>

				{/* Icon Gap */}
				<ResponsiveRangeControl
					attributes = { attributes }
					setAttributes = { setAttributes }
					attributeKeys = { {
						desktop: 'buttonIconGapDesktop',
						tablet: 'buttonIconGapTablet',
						mobile: 'buttonIconGapMobile'
					} }
					label = { __( 'Icon Gap', 'smart-social-media-buttons' ) }
					minValues = { { desktop: 0, tablet: 0, mobile: 0 } }
					maxValues = { { desktop: 100, tablet: 100, mobile: 100 } }
					defaultValue = { null }
					ResetComponent = { ResetIconButton }
					panelTitle = { __( 'Icon', 'smart-social-media-buttons' ) }
					blockType = 'ssmb/icon-button'
				/>
			</PanelBody>
		</>
	);
}
