'use client';

import { InputLayout } from '../input-layout/input-layout';
import React, { forwardRef, InputHTMLAttributes, useId, useState } from 'react';

interface SliderProps extends InputHTMLAttributes<HTMLInputElement> {
    options?: number[];
}

export const Slider = forwardRef<HTMLInputElement, SliderProps>(
    ({ options, ...props }, ref) => {
        const sliderId = useId();
        const [progress, setProgress] = useState<number>(0);

        return (
            <div className={'m3 m3-slider-container'}>
                <InputLayout
                    {...props}
                    className={props.className}
                    list={sliderId}
                    onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                        setProgress(
                            (parseInt(event.target.value) /
                                parseInt(event.target.max)) *
                                100,
                        );
                    }}
                    ref={ref}
                    style={{
                        ...props.style,
                        background: `linear-gradient(to right, var(--md-sys-color-primary) ${progress}%, var(--md-sys-color-surface-container-highest) ${progress}%)`,
                    }}
                    type={'range'}
                    typeInput={'slider'}
                />
                {options && (
                    <datalist id={sliderId}>
                        {options.map((option, index) => (
                            <option key={index} value={option} />
                        ))}
                    </datalist>
                )}
            </div>
        );
    },
);
