import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
	PanelBody,
	Button,
	Modal,
	__experimentalVStack as VStack,
	__experimentalHStack as HStack,
	__experimentalText as Text,
	__experimentalNumberControl as NumberControl,
	Notice,
	Spinner,
	CheckboxControl,
} from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';
import { DEFAULT_BREAKPOINTS } from '../../../../core/breakpoints';
import { isPlus } from '../../../../utils/is-pro';
import PlusFeatureOverlay from '../../../../blocks/common/components/PlusFeatureOverlay';

export const ResponsiveSettings = ( { initialOpen = false } ) => {
	const isPlusUser = isPlus();
	const [ breakpoints, setBreakpoints ] = useState( DEFAULT_BREAKPOINTS );
	const [ isLoading, setIsLoading ] = useState( true );
	const [ isSaving, setIsSaving ] = useState( false );
	const [ notice, setNotice ] = useState( null );
	const [ hasChanges, setHasChanges ] = useState( false );
	const [ showSaveModal, setShowSaveModal ] = useState( false );

	useEffect( () => {
		loadBreakpoints();
	}, [] );

	const loadBreakpoints = async () => {
		setIsLoading( true );
		try {
			const response = await apiFetch( {
				path: '/zenblocks/v1/breakpoints',
				method: 'GET',
			} );
			if ( response && response.breakpoints ) {
				setBreakpoints( response.breakpoints );
			}
		} catch ( error ) {
			console.error( 'Failed to load breakpoints:', error );
		}
		setIsLoading( false );
	};

	const saveBreakpoints = async () => {
		setIsSaving( true );
		setNotice( null );
		try {
			await apiFetch( {
				path: '/zenblocks/v1/breakpoints',
				method: 'POST',
				data: { breakpoints },
			} );
			setHasChanges( false );
			setShowSaveModal( true );
		} catch ( error ) {
			console.error( 'Failed to save breakpoints:', error );
			setNotice( {
				status: 'error',
				message: __( 'Failed to save', 'zenblocks' ),
			} );
		}
		setIsSaving( false );
	};

	const handleReload = () => {
		window.location.reload();
	};

	const resetToDefault = () => {
		setBreakpoints( DEFAULT_BREAKPOINTS );
		setHasChanges( true );
	};

	const updateBreakpointValue = ( key, value ) => {
		const numValue = parseInt( value, 10 );
		const finalValue =
			isNaN( numValue ) || numValue < 0
				? DEFAULT_BREAKPOINTS.values[ key ]
				: numValue;

		setBreakpoints( ( prev ) => ( {
			...prev,
			values: {
				...prev.values,
				[ key ]: finalValue,
			},
		} ) );
		setHasChanges( true );
	};

	const toggleBreakpoint = ( key ) => {
		if ( key === 'pc' ) {
			return;
		}

		setBreakpoints( ( prev ) => {
			const currentEnabled = prev.enabled || [];
			const isEnabled = currentEnabled.includes( key );

			let newEnabled;
			const newValues = { ...prev.values };

			if ( isEnabled ) {
				newEnabled = currentEnabled.filter( ( k ) => k !== key );
			} else {
				const order = [ 'pc', 'md', 'tb', 'sp' ];
				newEnabled = [ ...currentEnabled, key ].sort(
					( a, b ) => order.indexOf( a ) - order.indexOf( b )
				);
				if (
					newValues[ key ] === undefined ||
					newValues[ key ] === null ||
					isNaN( newValues[ key ] )
				) {
					newValues[ key ] = DEFAULT_BREAKPOINTS.values[ key ];
				}
			}

			return {
				...prev,
				enabled: newEnabled,
				values: newValues,
			};
		} );
		setHasChanges( true );
	};

	const getBreakpointRanges = () => {
		const ranges = [];
		const enabledList = enabled.filter( ( bp ) => bp !== 'pc' );

		const getValue = ( key ) => {
			const val = values[ key ];
			return val !== undefined && val !== null && ! isNaN( val )
				? val
				: DEFAULT_BREAKPOINTS.values[ key ];
		};

		if ( enabledList.length === 0 ) {
			ranges.push( {
				name: 'PC',
				range: __( 'All widths', 'zenblocks' ),
			} );
		} else {
			const sortedEnabled = [ 'pc', ...enabledList ].sort( ( a, b ) => {
				const order = [ 'pc', 'md', 'tb', 'sp' ];
				return order.indexOf( a ) - order.indexOf( b );
			} );

			for ( let i = 0; i < sortedEnabled.length; i++ ) {
				const bp = sortedEnabled[ i ];
				const nextBp = sortedEnabled[ i + 1 ];

				let min, max;

				const deviceNames = {
					pc: 'Desktop (PC)',
					md: 'Medium (MD)',
					tb: 'Tablet (TB)',
					sp: 'Mobile (SP)',
				};

				if ( bp === 'pc' ) {
					if ( nextBp ) {
						min = getValue( nextBp ) + 1;
					} else {
						min = getValue( 'tb' ) + 1;
					}
					ranges.push( {
						name: deviceNames.pc,
						range: `${ min }px 〜`,
					} );
				} else if ( bp === 'sp' ) {
					max = getValue( 'sp' );
					ranges.push( {
						name: deviceNames.sp,
						range: `〜 ${ max }px`,
					} );
				} else {
					max = getValue( bp );
					if ( nextBp ) {
						min = getValue( nextBp ) + 1;
					} else {
						min = 0;
					}
					ranges.push( {
						name: deviceNames[ bp ],
						range: `${ min }px 〜 ${ max }px`,
					} );
				}
			}
		}

		return ranges;
	};

	if ( isLoading ) {
		return (
			<PanelBody
				title={ __( 'Responsive', 'zenblocks' ) }
				initialOpen={ initialOpen }
				className="zenblocks-responsive-settings"
			>
				<div style={ { textAlign: 'center', padding: '20px' } }>
					<Spinner />
				</div>
			</PanelBody>
		);
	}

	const enabled = breakpoints.enabled || DEFAULT_BREAKPOINTS.enabled;
	const values = breakpoints.values || DEFAULT_BREAKPOINTS.values;
	const breakpointRanges = getBreakpointRanges();

	return (
		<>
			<PanelBody
				title={ __( 'Responsive', 'zenblocks' ) }
				initialOpen={ initialOpen }
				className="zenblocks-responsive-settings"
			>
				<PlusFeatureOverlay
					featureName={ __( 'Custom Breakpoints', 'zenblocks' ) }
					learnMorePath="/downloads/"
				>
					<VStack spacing={ 4 }>
						{ notice && (
							<Notice
								status={ notice.status }
								isDismissible
								onDismiss={ () => setNotice( null ) }
							>
								{ notice.message }
							</Notice>
						) }

						<Text className="zenblocks-responsive-settings__description">
							{ __(
								'Configure breakpoints for device-specific display',
								'zenblocks'
							) }
						</Text>

						<div className="zenblocks-responsive-settings__breakpoints">
							<VStack spacing={ 3 }>
								<HStack
									className="zenblocks-responsive-settings__row"
									spacing={ 3 }
									alignment="center"
								>
									<CheckboxControl
										className="zenblocks-responsive-settings__checkbox"
										checked={ true }
										disabled={ true }
										__nextHasNoMarginBottom
									/>
									<Text className="zenblocks-responsive-settings__label">
										PC
									</Text>
									<Text className="zenblocks-responsive-settings__note">
										{ __( 'Always enabled', 'zenblocks' ) }
									</Text>
								</HStack>

								<HStack
									className="zenblocks-responsive-settings__row"
									spacing={ 3 }
									alignment="center"
								>
									<CheckboxControl
										className="zenblocks-responsive-settings__checkbox"
										checked={ enabled.includes( 'md' ) }
										onChange={ () => toggleBreakpoint( 'md' ) }
										__nextHasNoMarginBottom
										disabled={ ! isPlusUser }
									/>
									<Text className="zenblocks-responsive-settings__label">
										MD
									</Text>
									<NumberControl
										className="zenblocks-responsive-settings__input"
										value={ values.md }
										onChange={ ( value ) =>
											updateBreakpointValue( 'md', value )
										}
										min={ values.tb + 1 }
										max={ 1920 }
										step={ 1 }
										hideHTMLArrows
										disabled={ ! isPlusUser || ! enabled.includes( 'md' ) }
									/>
								</HStack>

								<HStack
									className="zenblocks-responsive-settings__row"
									spacing={ 3 }
									alignment="center"
								>
									<CheckboxControl
										className="zenblocks-responsive-settings__checkbox"
										checked={ enabled.includes( 'tb' ) }
										onChange={ () => toggleBreakpoint( 'tb' ) }
										__nextHasNoMarginBottom
										disabled={ ! isPlusUser }
									/>
									<Text className="zenblocks-responsive-settings__label">
										TB
									</Text>
									<NumberControl
										className="zenblocks-responsive-settings__input"
										value={ values.tb }
										onChange={ ( value ) =>
											updateBreakpointValue( 'tb', value )
										}
										min={ values.sp + 1 }
										max={ values.md - 1 }
										step={ 1 }
										hideHTMLArrows
										disabled={ ! isPlusUser || ! enabled.includes( 'tb' ) }
									/>
								</HStack>

								<HStack
									className="zenblocks-responsive-settings__row"
									spacing={ 3 }
									alignment="center"
								>
									<CheckboxControl
										className="zenblocks-responsive-settings__checkbox"
										checked={ enabled.includes( 'sp' ) }
										onChange={ () => toggleBreakpoint( 'sp' ) }
										__nextHasNoMarginBottom
										disabled={ ! isPlusUser }
									/>
									<Text className="zenblocks-responsive-settings__label">
										SP
									</Text>
									<NumberControl
										className="zenblocks-responsive-settings__input"
										value={ values.sp }
										onChange={ ( value ) =>
											updateBreakpointValue( 'sp', value )
										}
										min={ 320 }
										max={ values.tb - 1 }
										step={ 1 }
										hideHTMLArrows
										disabled={ ! isPlusUser || ! enabled.includes( 'sp' ) }
									/>
								</HStack>
							</VStack>
						</div>

						<div className="zenblocks-responsive-settings__ranges">
							<Text className="zenblocks-responsive-settings__ranges-title">
								{ __( 'Breakpoint Ranges', 'zenblocks' ) }
							</Text>
							<VStack
								className="zenblocks-responsive-settings__ranges-list"
								spacing={ 1 }
							>
								{ breakpointRanges.map( ( item, index ) => (
									<HStack
										key={ index }
										className="zenblocks-responsive-settings__range-row"
										spacing={ 2 }
										alignment="center"
									>
										<Text className="zenblocks-responsive-settings__range-label">
											{ item.name }
										</Text>
										<Text className="zenblocks-responsive-settings__range-value">
											{ item.range }
										</Text>
									</HStack>
								) ) }
							</VStack>
						</div>

						<div className="zenblocks-responsive-settings__actions">
							<HStack spacing={ 2 }>
								<Button
									className="zenblocks-responsive-settings__save-button"
									variant="primary"
									onClick={ saveBreakpoints }
									isBusy={ isSaving }
									disabled={ ! isPlusUser || isSaving || ! hasChanges }
								>
									{ isSaving
										? __( 'Saving…', 'zenblocks' )
										: __( 'Save', 'zenblocks' ) }
								</Button>
								<Button
									className="zenblocks-responsive-settings__reset-button"
									variant="secondary"
									onClick={ resetToDefault }
									disabled={ ! isPlusUser || isSaving }
								>
									{ __( 'Reset', 'zenblocks' ) }
								</Button>
							</HStack>
						</div>

						<Text className="zenblocks-responsive-settings__footer-note">
							{ __(
								'Unsaved settings will be lost on page reload',
								'zenblocks'
							) }
						</Text>
					</VStack>
				</PlusFeatureOverlay>
			</PanelBody>

			{ showSaveModal && (
				<Modal
					title={ __( 'Saved', 'zenblocks' ) }
					onRequestClose={ () => setShowSaveModal( false ) }
					className="zenblocks-responsive-settings-modal"
				>
					<VStack spacing={ 4 }>
						<Text>
							{ __(
								'Breakpoint settings have been saved.',
								'zenblocks'
							) }
						</Text>
						<Text>
							{ __(
								'Please reload the page to apply changes.',
								'zenblocks'
							) }
						</Text>
						<Text className="zenblocks-responsive-settings-modal__note">
							{ __(
								'If you have other unsaved changes, please save them before reloading.',
								'zenblocks'
							) }
						</Text>
						<HStack spacing={ 2 } justify="flex-end">
							<Button
								variant="secondary"
								onClick={ () => setShowSaveModal( false ) }
							>
								{ __( 'Close', 'zenblocks' ) }
							</Button>
							<Button variant="primary" onClick={ handleReload }>
								{ __( 'Reload', 'zenblocks' ) }
							</Button>
						</HStack>
					</VStack>
				</Modal>
			) }
		</>
	);
};
