'use client';

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

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

export const Slider = forwardRef<HTMLInputElement, SliderProps>(
    ({ options, ...props }, ref) => {
        const sliderId = useId();
        const [isChrome, setIsChrome] = useState<boolean>(false);

        useLayoutEffect(() => {
            setIsChrome(navigator.userAgent.indexOf('AppleWebKit') != -1);
        }, []);

        return (
            <div className={'m3 m3-slider-container'}>
                <InputLayout
                    {...props}
                    className={props.className}
                    list={sliderId}
                    onChange={(event: ChangeEvent<HTMLInputElement>) => {
                        props.onChange?.apply(this, props?.onChange?.prototype);

                        if (isChrome) {
                            const fraction =
                                (parseInt(event.target.value) /
                                    parseInt(event.target.max)) *
                                100;
                            event.target.style.background = `linear-gradient(\
                            to right, var(--md-sys-color-primary) ${fraction}%, \
                            var(--md-sys-color-surface-container-highest) ${fraction}%\
                            )`;
                        }
                    }}
                    ref={ref}
                    type={'range'}
                    typeInput={'slider'}
                />
                {options && (
                    <datalist id={sliderId}>
                        {options.map((option, index) => (
                            <option key={index} value={option} />
                        ))}
                    </datalist>
                )}
            </div>
        );
    },
);
