/**
 * Slider Control Component
 * 
 * Elementor-style slider with:
 * - Visual range slider
 * - Numeric input with unit
 * - Min/max limits
 * 
 * @since 1.5.0
 */

import React from 'react';
import { 
    FieldValue, 
    PresetGlobalValues, 
    isGlobalRef, 
    createCustomValue,
    resolveFieldValue 
} from '../../../types/appearance';

interface SliderControlProps {
    label: string;
    value: FieldValue | undefined;
    globalValues: PresetGlobalValues;
    onChange: (value: FieldValue) => void;
    min: number;
    max: number;
    step?: number;
    unit?: 'px' | 'em' | 'rem' | '%' | '';
    defaultValue?: number;
    disabled?: boolean;
}

function parseValueWithUnit(valueStr: string | undefined, defaultUnit: string = 'px'): { num: number; unit: string } {
    if (!valueStr) return { num: 0, unit: defaultUnit };
    
    const match = valueStr.toString().match(/^([\d.]+)\s*(.*)$/);
    if (match) {
        return {
            num: parseFloat(match[1]) || 0,
            unit: match[2] || defaultUnit,
        };
    }
    
    const num = parseFloat(valueStr);
    return { num: isNaN(num) ? 0 : num, unit: defaultUnit };
}

export const SliderControl: React.FC<SliderControlProps> = ({
    label,
    value,
    globalValues,
    onChange,
    min,
    max,
    step = 1,
    unit = 'px',
    defaultValue = min,
    disabled = false,
}) => {
    const resolvedValue = resolveFieldValue(value || createCustomValue(`${defaultValue}${unit}`), globalValues);
    const { num: numValue, unit: currentUnit } = parseValueWithUnit(resolvedValue, unit);
    
    const isLinked = value ? isGlobalRef(value) : false;
    const clampedValue = Math.min(Math.max(numValue, min), max);
    
    const handleSliderChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const newValue = parseFloat(e.target.value);
        onChange(createCustomValue(`${newValue}${currentUnit}`));
    };
    
    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const newValue = parseFloat(e.target.value) || 0;
        onChange(createCustomValue(`${newValue}${currentUnit}`));
    };
    
    const fillPercent = ((clampedValue - min) / (max - min)) * 100;
    
    return (
        <div className="slider-control">
            <div className="flex items-center justify-between mb-1.5">
                <label className="text-xs text-gray-600 font-medium">{label}</label>
            </div>
            
            <div className={`flex items-center gap-3 ${isLinked ? 'opacity-60' : ''}`}>
                <div className="flex-1 relative">
                    <input
                        type="range"
                        min={min}
                        max={max}
                        step={step}
                        value={clampedValue}
                        onChange={handleSliderChange}
                        disabled={disabled || isLinked}
                        className="w-full h-1.5 bg-gray-200 rounded-full appearance-none cursor-pointer slider-thumb"
                        style={{
                            background: `linear-gradient(to left, #e5e7eb ${100 - fillPercent}%, #3BC2D0 ${100 - fillPercent}%)`,
                        }}
                    />
                </div>
                
                <div className="flex items-center bg-gray-50 border border-gray-200 rounded-md overflow-hidden">
                    <input
                        type="number"
                        step={step}
                        value={numValue}
                        onChange={handleInputChange}
                        onFocus={(e) => e.currentTarget.select()}
                        disabled={disabled || isLinked}
                        className="w-14 px-2 py-1 text-sm text-center bg-transparent border-none focus:outline-none focus:ring-0"
                    />
                    {unit && (
                        <span className="px-2 py-1 text-xs text-gray-500 bg-gray-100 border-r border-gray-200">
                            {unit}
                        </span>
                    )}
                </div>
            </div>
        </div>
    );
};

export default SliderControl;
