/**
 * SettingsPresets
 *
 * Preset selector and management UI: apply, save-as, delete, reset.
 *
 * Extracted from SettingsPanel.tsx in v1.4.0.
 *
 * @since 1.4.0
 */

import React, { useState } from 'react';
import { useCanvasSettings } from '../hooks/useCanvasSettings';

// --- Types ---

export interface SettingsPresetsProps {
	className?: string;
	selectClassName?: string;
	buttonClassName?: string;
	buttonsClassName?: string;
	inputClassName?: string;
}

// --- Component ---

export function SettingsPresets({
	className,
	selectClassName,
	buttonClassName,
	buttonsClassName,
	inputClassName,
}: SettingsPresetsProps) {
	const {
		allPresets,
		activePresetId,
		hasUnsavedChanges,
		applyPreset,
		saveAsPreset,
		deletePreset,
		resetSettings,
	} = useCanvasSettings();

	const [showSaveDialog, setShowSaveDialog] = useState(false);
	const [newPresetName, setNewPresetName] = useState('');

	const handleSave = () => {
		if (newPresetName.trim()) {
			saveAsPreset(newPresetName.trim());
			setNewPresetName('');
			setShowSaveDialog(false);
		}
	};

	const handleDelete = () => {
		if (activePresetId && !allPresets.find(p => p.id === activePresetId)?.isBuiltIn) {
			deletePreset(activePresetId);
		}
	};

	return (
		<div className={className}>
			<select
				className={selectClassName}
				value={activePresetId || ''}
				onChange={(e) => e.target.value && applyPreset(e.target.value)}
			>
				<option value="" disabled>
					{hasUnsavedChanges ? 'Custom (modified)' : 'Select preset...'}
				</option>
				{allPresets.map((preset) => (
					<option key={preset.id} value={preset.id}>
						{preset.name}
						{preset.isBuiltIn ? '' : ' (custom)'}
					</option>
				))}
			</select>

			<div className={buttonsClassName}>
				{showSaveDialog ? (
					<>
						<input
							type="text" className={inputClassName} placeholder="Preset name"
							value={newPresetName} onChange={(e) => setNewPresetName(e.target.value)}
							onKeyDown={(e) => e.key === 'Enter' && handleSave()} autoFocus
						/>
						<button className={buttonClassName} onClick={handleSave}>Save</button>
						<button className={buttonClassName} onClick={() => setShowSaveDialog(false)}>Cancel</button>
					</>
				) : (
					<>
						<button className={buttonClassName} onClick={() => setShowSaveDialog(true)}>Save as...</button>
						{activePresetId && !allPresets.find(p => p.id === activePresetId)?.isBuiltIn && (
							<button className={buttonClassName} onClick={handleDelete}>Delete</button>
						)}
						<button className={buttonClassName} onClick={resetSettings}>Reset</button>
					</>
				)}
			</div>
		</div>
	);
}
