import {
	useState,
	useEffect,
} from '@wordpress/element';

import {
	Flex,
	FlexBlock,
	Button,
	TextareaControl,
} from '@wordpress/components';

import ApuraToggle from './ApuraToggle';
import ApuraButtonGroup from './ApuraButtonGroup';

import { __ } from '@wordpress/i18n';


type Props = {
	subControlIds: string[];
	isOpen: boolean;
}

export default function SubControls({ subControlIds, isOpen }: Props) {
	const [subControlValues, setSubControlValues] = useState<any>({});


	useEffect(() => {
		const initialValues: any = {};
		const settingListeners: any = {};

		subControlIds.forEach((subControlId: string) => {
			try {
				const optionId = apuraCustomizerControl?.themeOptionField ? `${apuraCustomizerControl.themeOptionField}[${subControlId}]` : subControlId;
				const subControl = wp.customize.control(optionId);
				if (subControl && subControl.setting) {
					const setting = subControl.setting;
					initialValues[subControlId] = setting.get();

					// 設定値の変更を監視
					const listener = (newValue: any) => {
						setSubControlValues(prev => ({
							...prev,
							[subControlId]: newValue,
						}));
					};

					setting.bind(listener);
					settingListeners[subControlId] = { setting, listener };
				} else {
					console.warn(`SubControl not found: ${subControlId}`);
					initialValues[subControlId] = '';
				}
			} catch (error) {
				console.error(`Error accessing subControl ${subControlId}:`, error);
				initialValues[subControlId] = '';
			}
		});

		setSubControlValues(initialValues);

		// クリーンアップ関数
		return () => {
			Object.values(settingListeners).forEach((item: any) => {
				if (item.setting && item.listener) {
					item.setting.unbind(item.listener);
				}
			});
		};
	}, [subControlIds]);


	return (
		<Flex direction="column" gap="4" className="apura-sub-controls" style={isOpen ? {} : { display: 'none' }}>
			{subControlIds.map((subControlId: string) => {
				const subControl = wp.customize.control(subControlId);
				// サブコントロールが存在しない場合のエラーハンドリング.
				if (!subControl || !subControl.setting) {
					console.warn(`SubControl not found: ${subControlId}`);
					return null;
				}
				const setting = subControl.setting;
				const choices = subControl.params.choices;
				if (choices.type === 'textarea') {
					return (
						<FlexBlock key={subControlId}>
							<TextareaControl
								__nextHasNoMarginBottom
								label={subControl.params.label}
								value={subControlValues[subControlId]}
								help={subControl.params.description}
								onChange={(value) => {
									setting.set(value);
									setSubControlValues(prev => ({ ...prev, [subControlId]: value }));
								}}
							/>
						</FlexBlock>
					);
				}
				if (choices.type === 'number') {
					return (
						<FlexBlock key={subControlId}>
							<div className="apura-control-title">{subControl.params.label}</div>
							{subControl.params.description &&
								<p className="customize-control-description">{subControl.params.description}</p>
							}
							<input
								type="number"
								value={subControlValues[subControlId]}
								onChange={(e) => {
									const value = e.target.value;
									setting.set(value);
									setSubControlValues(prev => ({ ...prev, [subControlId]: value }));
								}}
								min={choices.min !== undefined ? choices.min : undefined}
								max={choices.max !== undefined ? choices.max : undefined}
								step={choices.step !== undefined ? choices.step : '1'}
							/>
						</FlexBlock>
					);
				}
				if (choices.type === 'select') {
					return (
						<FlexBlock key={subControlId}>
							<div className="apura-control-title">{subControl.params.label}</div>
							{subControl.params.description &&
								<p className="customize-control-description">{subControl.params.description}</p>
							}
							<select
								value={subControlValues[subControlId]}
								onChange={(e) => {
									setting.set(e.target.value);
									setSubControlValues(prev => ({ ...prev, [subControlId]: e.target.value }));
								}}
							>
								{Object.entries(choices.choices).map(([key, label]) => (
									<option value={key} key={key}>{label as string}</option>
								))}
							</select>
						</FlexBlock>
					);
				}
				if (choices.type === 'apura-button-group') {
					return (
						<FlexBlock key={subControlId}>
							<ApuraButtonGroup
								controlSetting={setting}
								title={subControl.params.label}
								description={subControl.params.description}
								value={subControlValues[subControlId] || setting.get()}
								choices={choices.choices}
							/>
						</FlexBlock>
					);
				}
				if (choices.type === 'apura-toggle') {
					return (
						<FlexBlock key={subControlId}>
							<ApuraToggle
								controlSetting={setting}
								isActive={setting.get()}
								title={subControl.params.label}
								description={subControl.params.description}
							/>
						</FlexBlock>
					);
				}
				if (choices.type === 'image') {
					return (
						<FlexBlock key={subControlId}>
							<div className="apura-control-title">{subControl.params.label}</div>
							{subControl.params.description &&
								<p className="customize-control-description">{subControl.params.description}</p>
							}
							{setting.get() && setting.get().url &&
								<img src={setting.get().url} alt="" style={{ maxWidth: '100%', height: 'auto', display: 'block', marginBlock: '8px' }} />
							}
							<Button
								variant="secondary"
								onClick={() => {
									const frame = wp.media({
										title: __('Select or Upload Image', 'apura'),
										button: {
											text: __('Use this image', 'apura'),
										},
										multiple: false,
									});
									frame.on('select', () => {
										const attachment = frame.state().get('selection').first().toJSON();
										setting.set(attachment);
										setSubControlValues(prev => ({ ...prev, [subControlId]: attachment }));
									});
									frame.open();
								}}
								style={{ marginRight: '8px' }}
							>
								{!setting.get() ? __('Select Image', 'apura') : __('Change Image', 'apura')}
							</Button>
							{setting.get() &&
								<Button
									isDestructive
									onClick={() => {
										setting.set('');
										setSubControlValues(prev => ({ ...prev, [subControlId]: '' }));
									}}
								>
									{__('Remove Image', 'apura')}
								</Button>
							}
						</FlexBlock>
					);
				}
				return (
					<FlexBlock key={subControlId}>
						<div className="apura-control-title">{subControl.params.label}</div>
						{subControl.params.description &&
							<p className="customize-control-description">{subControl.params.description}</p>
						}
						<input
							type='text'
							value={subControlValues[subControlId]}
							onChange={(e) => {
								setting.set(e.target.value);
								setSubControlValues(prev => ({ ...prev, [subControlId]: e.target.value }));
							}}
						/>
					</FlexBlock>
				);
			})}
		</Flex>
	);
}
