import classNames from "classnames";
import React, { useEffect, useRef, useState } from "react";
import { BubbleContent } from "../bubble";
import { Popover } from "../popover";
import { SliderHandleProps } from "./SliderProps";

export function SliderHandle({
  classPrefix,
  value,
  vertical,
  offset,
  dragging,
  enableTip,
  tipFormatter,
}: SliderHandleProps) {
  const [hovering, setHovering] = useState(false);
  const scheduleRef = useRef(null);

  const offsetKey = vertical ? "bottom" : "left";

  useEffect(() => {
    if (scheduleRef.current) {
      scheduleRef.current();
    }
  }, [offset]);

  return (
    <Popover
      visible={enableTip && (dragging || hovering)}
      overlayStyle={{
        pointerEvents: "none",
      }}
      placement={vertical ? "left" : "top"}
      transitionTimeout={0}
      overlay={({ placement, scheduleUpdate }) => {
        scheduleRef.current = scheduleUpdate;
        const tips = tipFormatter(value);
        return (
          tips !== null && (
            <BubbleContent placement={placement}>{tips}</BubbleContent>
          )
        );
      }}
    >
      <div
        className={`${classPrefix}-slider__handle`}
        style={{ [offsetKey]: `${offset}%` }}
        onMouseEnter={() => setHovering(true)}
        onMouseLeave={() => setHovering(false)}
      >
        <span
          className={classNames(`${classPrefix}-slider__handle-inner`, {
            "is-active": hovering || dragging,
          })}
        />
      </div>
    </Popover>
  );
}

SliderHandle.displayName = "SliderHandle";
