import { InspectorControls, PanelColorSettings } from "@wordpress/block-editor";
import { __ } from '@wordpress/i18n';
import { PanelBody, ToggleControl } from "@wordpress/components";
import { useState, useEffect } from "@wordpress/element";

const SidePanel = ({ attributes, setAttributes }) => {
	// Get theme colors and store them in state to avoid recalculating
	const [themeColors, setThemeColors] = useState({
		background: '#ffffff',
		text: '#172B4D',
		border: '#e0e0e0'
	});

	useEffect(() => {
		const colors = window.OrphicWPBlockOptions.orphic_wp_block_plugin_colors || [];
		if (colors.length > 0) {
			setThemeColors({
				background: colors.find(c => c.slug === 'background')?.color || themeColors.background,
				text: colors.find(c => c.slug === 'text')?.color || themeColors.text,
				border: colors.find(c => c.slug === 'border')?.color || themeColors.border
			});
		}
	}, []);

	return (
		<InspectorControls>
			<PanelBody title={__('Testimonial Settings', 'orphic-ui')}>
				<ToggleControl
					label={__('Show Image', 'orphic-ui')}
					checked={attributes.showImage}
					onChange={(value) => setAttributes({ showImage: value })}
				/>
				
				<ToggleControl
					label={__("Use custom color", "orphic-ui")} 
					checked={attributes.isCustomColor} 
					onChange={(value) => {setAttributes({isCustomColor: value})}}
				/>
				
				{attributes.isCustomColor && (
					<PanelColorSettings
						title={__("Color Settings", "orphic-ui")}
						enableAlpha
						colorSettings={[
							{
								value: attributes.backgroundColor,
								onChange: (color) => setAttributes({backgroundColor: color || themeColors.background}),
								label: __("Background Color", "orphic-ui"),
								resetFallbackColor: themeColors.background,
							},
							{
								value: attributes.textColor,
								onChange: (color) => setAttributes({textColor: color || themeColors.text}),
								label: __("Text Color", "orphic-ui"),
								resetFallbackColor: themeColors.text,
							},
							{
								value: attributes.borderColor,
								onChange: (color) => setAttributes({borderColor: color || themeColors.border}),
								label: __("Border Color", "orphic-ui"),
								resetFallbackColor: themeColors.border,
							},
						]}
					/>
				)}
			</PanelBody>
		</InspectorControls>
	);
};

export default SidePanel;
