import React, { useCallback, useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { v4 as uuidv4 } from 'uuid';

export enum RangeSliderType {
  Slider = 'rpgui-slider',
  GoldSlider = 'rpgui-slider golden',
}

export interface IRangeSliderProps {
  type: RangeSliderType;
  valueMin: number;
  valueMax: number;
  width: string;
  onChange: (value: number) => void;
  value: number;
  step?: number;
}

export const RangeSlider: React.FC<IRangeSliderProps> = React.memo(
  ({ type, valueMin, valueMax, width, onChange, value, step = 1 }) => {
    const sliderId = uuidv4();

    const containerRef = useRef<HTMLDivElement>(null);
    const [left, setLeft] = useState(0);

    useEffect(() => {
      const calculatedWidth = containerRef.current?.clientWidth || 0;
      setLeft(
        Math.max(
          ((value - valueMin) / (valueMax - valueMin)) *
            (calculatedWidth - 35) +
            10
        )
      );
    }, [value, valueMin, valueMax]);

    const typeClass = type === RangeSliderType.GoldSlider ? 'golden' : '';

    const handleChange = useCallback(
      (e: { target: { value: any } }) => {
        onChange(Number(e.target.value));
      },
      [onChange]
    );

    return (
      <div
        style={{ width: width, position: 'relative' }}
        className={`rpgui-slider-container ${typeClass}`}
        id={`rpgui-slider-${sliderId}`}
        ref={containerRef}
      >
        <div style={{ pointerEvents: 'none' }}>
          <div className={`rpgui-slider-track ${typeClass}`} />
          <div className={`rpgui-slider-left-edge ${typeClass}`} />
          <div className={`rpgui-slider-right-edge ${typeClass}`} />
          <div className={`rpgui-slider-thumb ${typeClass}`} style={{ left }} />
        </div>
        <Input
          type="range"
          style={{ width: width }}
          min={valueMin}
          max={valueMax}
          step={step}
          onChange={handleChange}
          value={value}
          className="rpgui-cursor-point"
        />
      </div>
    );
  }
);

const Input = styled.input`
  opacity: 0;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  margin-top: -5px;
`;
