import type { CSSProperties } from 'react';

const HEX_COLOR = /^#[0-9a-f]{6}$/i;
const SHORT_HEX_COLOR = /^#[0-9a-f]{3}$/i;

function normalizeHexColor(value: string, fallback: string): string {
	const trimmed = value.trim();
	if (HEX_COLOR.test(trimmed)) {
		return trimmed.toLowerCase();
	}
	if (SHORT_HEX_COLOR.test(trimmed)) {
		const [, r, g, b] = trimmed.toLowerCase();
		return `#${r}${r}${g}${g}${b}${b}`;
	}
	if (/^[0-9a-f]{6}$/i.test(trimmed)) {
		return `#${trimmed.toLowerCase()}`;
	}
	return fallback;
}

interface ColorControlProps {
	value: string;
	onChange: (value: string) => void;
	label: string;
	disabled?: boolean;
	inputId?: string;
	fallback?: string;
}

export function ColorControl({ value, onChange, label, disabled = false, inputId, fallback = '#2563eb' }: ColorControlProps) {
	const safeFallback = HEX_COLOR.test(fallback) ? fallback.toLowerCase() : '#2563eb';
	const pickerValue = HEX_COLOR.test(value.trim()) ? value.trim().toLowerCase() : safeFallback;
	const style = { '--stockbeacon-picker-color': pickerValue } as CSSProperties;

	return (
		<div className="stockbeacon-color-row" style={style}>
			<input
				type="text"
				id={inputId}
				className="regular-text stockbeacon-color-row__hex"
				aria-label={`${label} hex value`}
				autoComplete="off"
				autoCapitalize="off"
				spellCheck={false}
				disabled={disabled}
				value={value}
				placeholder={safeFallback}
				onChange={(e) => onChange(e.target.value)}
				onBlur={(e) => onChange(normalizeHexColor(e.target.value, pickerValue))}
			/>
			<span className="stockbeacon-color-row__picker" title={`${label} picker`}>
				<input
					type="color"
					aria-label={`${label} picker`}
					disabled={disabled}
					value={pickerValue}
					onChange={(e) => onChange(e.target.value)}
				/>
			</span>
		</div>
	);
}
