import React, {
  useEffect, useState, useRef, useCallback,
} from 'react';

import {
  Container, Wrapper, Rail, Track,
} from './styled';

type Props = {
  color?: 'primary' | 'secondary';
  max?: number;
  min?: number;
  defaultValue?: number;
  disabled?: boolean;
  onChange?: (value: number | number[]) => void;
};

const Sliders: React.FunctionComponent<Props> = ({
  defaultValue = 0,
  onChange,
}: Props) => {
  const sliderRef = useRef<HTMLDivElement>(null);
  const [valueState, setValueState] = useState(defaultValue);
  const [isActive, setActive] = useState(false);

  const parseValueToPercent = (value: number): number => Math.floor(value * 100);

  const getFingerMoveValue = (event: MouseEvent | React.MouseEvent<HTMLElement>): void => {
    const { current: slider } = sliderRef;

    if (slider) {
      const { width, left } = slider.getBoundingClientRect();
      const value = (event.clientX - left) / width;
      let percent = parseValueToPercent(value);

      if (percent <= 0) {
        percent = 0;
      } else if (percent >= 100) {
        percent = 100;
      }

      setValueState(percent);
      if (onChange) onChange(percent);
    }
  };

  const handleTouchMove = useCallback((event: MouseEvent) => {
    event.preventDefault();
    getFingerMoveValue(event);
  }, []);

  const handleTouchEnd = useCallback((event: MouseEvent) => {
    event.preventDefault();

    setActive(false);
    document.body.removeEventListener('mousemove', handleTouchMove);
  }, []);

  const handleMouseDown = useCallback((event: React.MouseEvent<HTMLElement>) => {
    event.preventDefault();

    getFingerMoveValue(event);
    setActive(true);

    document.body.addEventListener('mousemove', handleTouchMove);
    document.body.addEventListener('mouseup', handleTouchEnd);
  }, []);

  useEffect(() => {
    setValueState(defaultValue);
  }, []);

  return (
    <Container>
      <Wrapper
        ref={sliderRef}
        onMouseDown={handleMouseDown}
      >
        <Rail track={valueState} />
        <Track
          track={valueState}
          isActive={isActive}
        />
      </Wrapper>
    </Container>
  );
};

export default Sliders;
