import { useState } from '@wordpress/element';
import { ButtonGroup, Button, ToggleControl, TextControl, SelectControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import SegmentedSlider from '../../SegmentedSlider';
import CustomRange from '../../CustomRange';

const DEVICE_BREAKPOINTS = [
	{ label: __('Mobile', 'easy-dropbox-integration'), value: 'mobile' },
	{ label: __('Tablet', 'easy-dropbox-integration'), value: 'tablet' },
	{ label: __('Laptop', 'easy-dropbox-integration'), value: 'laptop' },
	{ label: __('Desktop', 'easy-dropbox-integration'), value: 'desktop' },
	{ label: __('Large Desktop', 'easy-dropbox-integration'), value: 'largeDesktop' },
];

const SLIDES_PER_PAGE_DEFAULTS = {
	mobile: 1,
	tablet: 2,
	laptop: 3,
	desktop: 4,
	largeDesktop: 5,
};

const OVERLAY_DISPLAY_OPTIONS = [
	{ label: __('Always', 'easy-dropbox-integration'), value: 'always' },
	{ label: __('On Hover', 'easy-dropbox-integration'), value: 'onHover' },
];

const SORT_BY_OPTIONS = [
	{ label: __('Name', 'easy-dropbox-integration'), value: 'name' },
	{ label: __('Date', 'easy-dropbox-integration'), value: 'date' },
	{ label: __('Size', 'easy-dropbox-integration'), value: 'size' },
];

const SORT_ORDER_OPTIONS = [
	{ label: __('Ascending', 'easy-dropbox-integration'), value: 'asc' },
	{ label: __('Descending', 'easy-dropbox-integration'), value: 'desc' },
];

const DEFAULT_IMAGE_SIZE_CONFIG = {
	mode: 'wp',
	wpSize: 'full',
	custom: {
		width: '',
		height: '',
	},
};

const SliderCarousel = ({ shortCodeConfig, updateShortCodeConfig }) => {
	const [activeDevice, setActiveDevice] = useState('mobile');
	const settings = shortCodeConfig?.settings || {};
	const sliderConfig = settings.sliderCarousel || {};
	const slidesPerPage = sliderConfig.slidesPerPage || SLIDES_PER_PAGE_DEFAULTS;
	const activeSlidesValue =
		slidesPerPage[activeDevice] ?? SLIDES_PER_PAGE_DEFAULTS[activeDevice];

	const rawImageSizes = (typeof window !== 'undefined' && window?.EDBIData?.imageSizes) || {};
	const normalizedImageSize = (() => {
		const config = sliderConfig.imageSize;
		if (config && typeof config === 'object') {
			return {
				...DEFAULT_IMAGE_SIZE_CONFIG,
				...config,
				custom: {
					width: config.custom?.width ?? '',
					height: config.custom?.height ?? '',
				},
			};
		}
		return DEFAULT_IMAGE_SIZE_CONFIG;
	})();

	const imageSizeMode = normalizedImageSize.mode === 'custom' ? 'custom' : 'wp';
	const imageSizeValue =
		imageSizeMode === 'custom' ? 'custom' : normalizedImageSize.wpSize || 'full';
	const customImageWidth = normalizedImageSize.custom?.width ?? '';
	const customImageHeight = normalizedImageSize.custom?.height ?? '';

	const imageSizeOptions = Object.keys(rawImageSizes).map((sizeKey) => {
		const size = rawImageSizes[sizeKey] || {};
		const widthLabel = size.width && size.width > 0 ? size.width : __('auto', 'easy-dropbox-integration');
		const heightLabel = size.height && size.height > 0 ? size.height : __('auto', 'easy-dropbox-integration');
		return {
			value: sizeKey,
			label: `${sizeKey} (${widthLabel} x ${heightLabel})`,
		};
	});
	const normalizedImageSizeOptions = imageSizeOptions.length
		? imageSizeOptions
		: [
				{
					value: 'full',
					label: __('Full (Original)', 'easy-dropbox-integration'),
				},
		  ];
	const imageSizeSelectOptions = [
		...normalizedImageSizeOptions,
		{
			value: 'custom',
			label: __('Custom (Width x Height)', 'easy-dropbox-integration'),
		},
	];

	const updateSliderConfig = (updates) => {
		updateShortCodeConfig('settings', {
			...settings,
			sliderCarousel: {
				...sliderConfig,
				...updates,
			},
		});
	};

	const handleImageSizeChange = (value) => {
		const updated = {
			...normalizedImageSize,
			mode: value === 'custom' ? 'custom' : 'wp',
			wpSize: value === 'custom' ? normalizedImageSize.wpSize || 'full' : value,
		};
		updateSliderConfig({ imageSize: updated });
	};

	const handleCustomDimensionChange = (field, value) => {
		const sanitized = value.replace(/[^0-9]/g, '');
		updateSliderConfig({
			imageSize: {
				...normalizedImageSize,
				mode: 'custom',
				custom: {
					...normalizedImageSize.custom,
					[field]: sanitized,
				},
			},
		});
	};

	return (
		<>
			<div className='edbi-shortcode-builder__container'>
				<div className='edbi-shortcode-builder__overlay__header'>
					<h3>{__('Slide Dimensions', 'easy-dropbox-integration')}</h3>
				</div>
				<div className='edbi-shortcode-builder__overlay__settings edbi-extend-wp-core-input'>
					<TextControl
						label={__('Slide Height', 'easy-dropbox-integration')}
						value={sliderConfig.slideHeight || ''}
						onChange={(value) => updateSliderConfig({ slideHeight: value })}
						placeholder={__('e.g. 360px', 'easy-dropbox-integration')}
					/>
					<div>
						<SelectControl
							label={__('Image Size', 'easy-dropbox-integration')}
							value={imageSizeValue}
							options={imageSizeSelectOptions}
							onChange={handleImageSizeChange}
						/>
					</div>
					{imageSizeMode === 'custom' && (
						<div style={{ display: 'flex', gap: '10px' }}>
							<TextControl
								label={__('Width (px)', 'easy-dropbox-integration')}
								value={customImageWidth}
								type='number'
								min='0'
								onChange={(value) => handleCustomDimensionChange('width', value)}
							/> 
							<TextControl
								label={__('Height (px)', 'easy-dropbox-integration')}
								value={customImageHeight}
								type='number'
								min='0'
								onChange={(value) => handleCustomDimensionChange('height', value)}
							/>
						</div>
					)}
				</div>
			</div>

			<div className='edbi-shortcode-builder__container'>
				<div className='edbi-shortcode-builder__overlay__header'>
					<h3>{__('Slides Per Page', 'easy-dropbox-integration')}</h3>
				</div>
				<div className='edbi-shortcode-builder__columns'>
					<div>
						<ButtonGroup className='edbi-shortcode-builder__columns-button'>
							{DEVICE_BREAKPOINTS.map((device, idx) => (
								<Button
									key={device.value}
									className={`edbi-shortcode-builder__columns-button__button ${
										activeDevice === device.value
											? 'edbi-shortcode-builder__columns-button__button--active'
											: ''
									} ${idx !== DEVICE_BREAKPOINTS.length - 1 ? 'edbi-right-border' : ''}`}
									onClick={() => setActiveDevice(device.value)}
								>
									{device.label}
								</Button>
							))}
						</ButtonGroup>
					</div>
					<SegmentedSlider
						value={activeSlidesValue}
						min={1}
						max={10}
						onChange={(value) =>
							updateSliderConfig({
								slidesPerPage: {
									...slidesPerPage,
									[activeDevice]: value,
								},
							})
						}
					/>
				</div>
			</div>

			<div className='edbi-shortcode-builder__container'>
				<div className='edbi-shortcode-builder__overlay__header'>
					<h3>{__('Behavior', 'easy-dropbox-integration')}</h3>
				</div>
				<div className='edbi-shortcode-builder__overlay__settings'>
					<ToggleControl
						label={__('Slide AutoPlay', 'easy-dropbox-integration')}
						checked={sliderConfig.autoPlay ?? false}
						onChange={(value) => updateSliderConfig({ autoPlay: value })}
					/>
					<ToggleControl
						label={__('Slide Arrows Navigation', 'easy-dropbox-integration')}
						checked={sliderConfig.arrowsNavigation ?? true}
						onChange={(value) => updateSliderConfig({ arrowsNavigation: value })}
					/>
					<CustomRange
						label={__('Gap', 'easy-dropbox-integration')}
						value={sliderConfig.gap ?? 0}
						min={0}
						max={60}
						onChange={(value) => updateSliderConfig({ gap: value })}
					/>
					<CustomRange
						label={__('Auto Play Speed (ms)', 'easy-dropbox-integration')}
						value={sliderConfig.autoPlaySpeed ?? 4000}
						min={100}
						max={10000}
						step={100}
						onChange={(value) => updateSliderConfig({ autoPlaySpeed: value })}
					/>
				</div>
			</div>

			<div className='edbi-shortcode-builder__container'>
				<div className='edbi-shortcode-builder__overlay__header'>
					<h3>{__('Overlay', 'easy-dropbox-integration')}</h3>
					<ToggleControl
						label={__('Show Overlay', 'easy-dropbox-integration')}
						checked={sliderConfig.showOverlay ?? true}
						onChange={(value) => updateSliderConfig({ showOverlay: value })}
					/>
				</div>

				{sliderConfig.showOverlay && (
					<div className='edbi-shortcode-builder__overlay__settings'>
						<h3 className='edbi-shortcode-builder__overlay__label'>
							{__('Overlay display type', 'easy-dropbox-integration')}
						</h3>
						<ButtonGroup className='edbi-shortcode-builder__thumbnail-view__buttons'>
							{OVERLAY_DISPLAY_OPTIONS.map((option, idx) => (
								<Button
									key={option.value}
									className={`edbi-shortcode-builder__thumbnail-view__button ${
										sliderConfig.overlayDisplay === option.value
											? 'edbi-shortcode-builder__thumbnail-view__button--active'
											: ''
									} ${idx < OVERLAY_DISPLAY_OPTIONS.length - 1 ? 'edbi-right-border' : ''}`}
									onClick={() => updateSliderConfig({ overlayDisplay: option.value })}
								>
									{option.label}
								</Button>
							))}
						</ButtonGroup>

						<ToggleControl
							label={__('Show title', 'easy-dropbox-integration')}
							checked={sliderConfig.showTitle ?? true}
							onChange={(value) => updateSliderConfig({ showTitle: value })}
						/>
						<ToggleControl
							label={__('Show description', 'easy-dropbox-integration')}
							checked={sliderConfig.showDescription ?? true}
							onChange={(value) => updateSliderConfig({ showDescription: value })}
						/>
						<ToggleControl
							label={__('Show size', 'easy-dropbox-integration')}
							checked={sliderConfig.showSize ?? false}
							onChange={(value) => updateSliderConfig({ showSize: value })}
						/>
					</div>
				)}
			</div>

			<div className='edbi-shortcode-builder__container'>
				<div className='edbi-shortcode-builder__overlay__header'>
					<h3>{__('Sorting', 'easy-dropbox-integration')}</h3>
				</div>
				<div className='edbi-shortcode-builder__thumbnail-view'>
					<h3>{__('Sort By', 'easy-dropbox-integration')}</h3>
					<ButtonGroup className='edbi-shortcode-builder__thumbnail-view__buttons'>
						{SORT_BY_OPTIONS.map((option, idx) => (
							<Button
								key={option.value}
								className={`edbi-shortcode-builder__thumbnail-view__button ${
									sliderConfig.sortBy === option.value
										? 'edbi-shortcode-builder__thumbnail-view__button--active'
										: ''
								} ${idx < SORT_BY_OPTIONS.length - 1 ? 'edbi-right-border' : ''}`}
								onClick={() => updateSliderConfig({ sortBy: option.value })}
							>
								{option.label}
							</Button>
						))}
					</ButtonGroup>
				</div>

				<div className='edbi-shortcode-builder__thumbnail-view'>
					<h3>{__('Sort Order', 'easy-dropbox-integration')}</h3>
					<ButtonGroup className='edbi-shortcode-builder__thumbnail-view__buttons'>
						{SORT_ORDER_OPTIONS.map((option, idx) => (
							<Button
								key={option.value}
								className={`edbi-shortcode-builder__thumbnail-view__button ${
									sliderConfig.sortOrder === option.value
										? 'edbi-shortcode-builder__thumbnail-view__button--active'
										: ''
								} ${idx < SORT_ORDER_OPTIONS.length - 1 ? 'edbi-right-border' : ''}`}
								onClick={() => updateSliderConfig({ sortOrder: option.value })}
							>
								{option.label}
							</Button>
						))}
					</ButtonGroup>
				</div>
			</div>
		</>
	);
};

export default SliderCarousel;
