import {
	useState,
	useEffect
} from '@wordpress/element';
import {
	Flex,
	FlexBlock,
	RangeControl,
	TextControl,
	Button,
	Notice,
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';

import { parseRangeToArray } from './utils';


type Props = {
	fontItem: GoogleFontItem;
	range: string;
	isWeightOneValue: boolean;
	widthData?: { range: string, default: string };
	isWidthOneValue?: boolean;
	onChange: (newValues: GoogleFontItem) => void;
};

// 注意：fontStyle, fontWidthは未実装で進める.
export default function GoogleVariableFontSettings({ fontItem, range, widthData, isWeightOneValue, isWidthOneValue, onChange }: Props) {
	const [weight, setWeight] = useState(fontItem.variants[0]);
	const [isWeightCustom, setIsWeightCustom] = useState<boolean>(isWeightOneValue);

	const allWeights = parseRangeToArray(range);

	// 親から渡されたpropsの変更に応じて状態を更新
	useEffect(() => {
		// setFontStyle(fontItem.italic);
		setWeight(fontItem.variants[0]);
		setIsWeightCustom(isWeightOneValue);
		// setFontWidth(fontItem.width);
	}, [fontItem]);


	// onChangeのロジック
	useEffect(() => {
		onChange({
			...fontItem,
			variants: [weight],
		});

	}, [weight, isWeightCustom]);

	return (
		<div className="apura-google-variable-font-control">
			<Flex direction="column" gap={2}>
				{/* Weight options */}
				<FlexBlock>
					<span className="customize-control-title">{__('Weight', 'apura')}</span>
					<div className="apura-button-group">
						<div className="apura-button-group__item">
							<Button
								className="apura-button"
								isPressed={!isWeightCustom}
								onClick={() => {
									setIsWeightCustom(false);
									setWeight(range);
								}}
							>
								{__('Full range', 'apura')}
							</Button>
						</div>
						<div className="apura-button-group__item">
							<Button
								className="apura-button"
								isPressed={isWeightCustom}
								onClick={() => {
									setIsWeightCustom(true);
									setWeight('400');
								}}
							>
								{__('One value', 'apura')}
							</Button>
						</div>
					</div>
				</FlexBlock>
				{/* Weight selector */}
				<FlexBlock>
					{isWeightCustom ? (
						<RangeControl
							__next40pxDefaultSize
							__nextHasNoMarginBottom
							value={Number(weight) || 400}
							onChange={(value) => setWeight(value?.toString() || '400')}
							allowReset
							initialPosition={400}
							min={Number(allWeights[0]) || 100}
							max={Number(allWeights[allWeights.length - 1]) || 900}
							step={1}
						/>
					) : (
						<TextControl
							__next40pxDefaultSize
							__nextHasNoMarginBottom
							readOnly
							value={weight}
							onChange={() => {}}
						/>
					)}
				</FlexBlock>
			</Flex>
		</div>
	);
}
