import React from "react";
import styled from "styled-components";

const RangeMeterWrapper = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 22px;
  height: 12px;
  position: relative;
`;

const ThresholdsWrapper = styled.div`
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 12px;
  border-radius: 22px;
  overflow: hidden;
  position: absolute;
`;

const Threshold = styled.div`
  width: ${(props) => props.width}%;
  height: 100%;
  border-radius: 22px;
  background-color: ${(props) => props.color};
`;

const RangeTrack = styled.input.attrs((props) => ({
  type: "range",
  min: props.min,
  max: props.max,
  value: props.value,
}))`
  -webkit-appearance: none;
  width: 100%;
  height: 100%;
  background-color: transparent;
  border-radius: 5px;
  outline: none;
  margin: 10px 0;
  position: relative;

  &::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background-color: #ffffff;
    border: 2px solid ${(props) => props.thresholdColor};
    cursor: pointer;
    position: relative;
    z-index: 1;
  }

  &::-moz-range-thumb {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background-color: #ffffff;
    border: 2px solid ${(props) => props.thresholdColor};
    cursor: pointer;
    position: relative;
    z-index: 1;
  }
`;

const ThumbTooltip = styled.div`
  position: absolute;
  top: -35px;
  left: ${(props) => props.value}%;
  transform: translateX(-50%);
  background-color: #ffffff;
  color: #000000;
  font-size: 14px;
  padding: 3px 5px;
  /* padding: 5px; */
  border-radius: px;
  display: block;
`;

const RangeMeter = ({ min, max, thresholds, value, onChange }) => {
  const trackRef = React.useRef(null);
  const thumbRef = React.useRef(null);
  const tooltipRef = React.useRef(null);

  const [thumbPosition, setThumbPosition] = React.useState({ x: 0, y: 0 });
  const [tooltipVisible, setTooltipVisible] = React.useState(false);

  const handleThumbMouseMove = (event) => {
    const trackRect = trackRef.current.getBoundingClientRect();
    const thumbRect = thumbRef.current.getBoundingClientRect();
    const tooltipRect = tooltipRef.current.getBoundingClientRect();

    const thumbPosition = {
      x: event.clientX - trackRect.left - thumbRect.width / 2,
      y: -tooltipRect.height - thumbRect.height,
    };

    setThumbPosition(thumbPosition);
  };

  const handleThumbMouseEnter = () => {
    setTooltipVisible(true);
  };

  const handleThumbMouseLeave = () => {
    setTooltipVisible(false);
  };

  const handleTrackChange = (event) => {
    const value = parseInt(event.target.value);
    const threshold = thresholds.find((threshold) => value < threshold.value);
    const thresholdColor = threshold
      ? threshold.color
      : thresholds[thresholds.length - 1].color;

    onChange(value, thresholdColor);
  };

  React.useEffect(() => {
    const thumb = thumbRef.current;

    if (thumb) {
      thumb.addEventListener("mousemove", handleThumbMouseMove);
      thumb.addEventListener("mouseenter", handleThumbMouseEnter);
      thumb.addEventListener("mouseleave", handleThumbMouseLeave);
    }

    return () => {
      if (thumb) {
        thumb.removeEventListener("mousemove", handleThumbMouseMove);
        thumb.removeEventListener("mouseenter", handleThumbMouseEnter);
        thumb.removeEventListener("mouseleave", handleThumbMouseLeave);
      }
    };
  }, [thumbRef]);
  const thresholdWidths = thresholds.map((threshold, index) => {
    const start = index === 0 ? min : thresholds[index - 1].value;
    const end = threshold.value ;
    const percentage = ((end - start) / (max - min)) * 100;
    return percentage;
  });

  const thresholdColors = thresholds.map((threshold) => threshold.color);

  return (
    <RangeMeterWrapper>
      <ThresholdsWrapper>
        {thresholds.map((threshold, index) => (
          <Threshold
            key={index}
            color={threshold.color}
            width={thresholdWidths[index]}
          />
        ))}
      </ThresholdsWrapper>
      <RangeTrack
        ref={trackRef}
        min={min}
        max={max}
        value={value}
        thresholdColor={thresholdColors.find(
          (color, index) =>
            value >= (index > 0 ? thresholds[index - 1].value : min) &&
            value < thresholds[index].value
        )}
        onChange={handleTrackChange}
        onMouseEnter={handleThumbMouseEnter}
        onMouseLeave={handleThumbMouseLeave}
      />
      <ThumbTooltip
        ref={tooltipRef}
        value={value}
        thumbPosition={thumbPosition}
        visible={tooltipVisible}
      >
        {value}
      </ThumbTooltip>
    </RangeMeterWrapper>
  );
};

export default RangeMeter;
