/**
 * @Author: ??
 * @Date: ??
 */
import React, { useCallback, useRef } from "react";
import { SliderProps } from "./interface";
import RcSlider, { SliderProps as RcSliderProps } from "rc-slider";
import "rc-slider/assets/index.css";
import SliderConfig from "./SliderConfig";
import "./index.css";

/**
 * ### 引用方法
 * ```tsx
 * import { Slider } from "@atomintl/exchange-ui";
 * ```
 * ####更多使用：https://github.com/react-component/slider
 */
export const Slider: React.FC<SliderProps & RcSliderProps> = props => {
  const { onSliderChange, adsorptionRadius, sliderValue, tipFormatter } = props;
  // const [value, setValue] = useState(defaultValue ?? SliderConfig.defaultValue);

  const handle = (child: React.ReactNode) => {
    const { transform } = child?.props?.style;
    return (
      <div {...child?.props}>
        <div className={`custom-rc-tooltip invisible`}>
          <div
            className={`absolute -top-[33px] bg-gray-5 text-black px-[9px] py-[3px] rounded-[4px] text-[12px] font-medium left-[6px]`}
            style={{ transform }}
          >
            <div>
              {tipFormatter ? tipFormatter(child.props?.["aria-valuenow"]) : `${child.props?.["aria-valuenow"]}%`}
            </div>
          </div>
          <div
            className={`w-0 h-0 border-[5px] border-solid border-transparent border-t-gray-5 absolute -top-[10px] left-px`}
          ></div>
        </div>
      </div>
    );
  };

  const ADJUST_NUM = adsorptionRadius ?? 5;
  const touchStatus = useRef<boolean>(false);
  const runTime = useRef<number>(0);

  const onBeforeChange = () => {
    touchStatus.current = true;
    runTime.current = 0;
  };
  const onChange = (val: number | number[]) => {
    ++runTime.current;
    onSliderChange(Number(val));
  };
  const onAfterChange = (val: number | number[]) => {
    touchStatus.current = false;
    if (runTime.current <= 1) {
      Object.keys(SliderConfig.marks).forEach(_item => {
        const n = Number(_item);
        if (val >= n - ADJUST_NUM && val <= n + ADJUST_NUM) {
          val = n;
        }
      });
      onSliderChange(Number(val));
    }
  };

  return (
    <div className={`px-[8px] ${props?.marks ? "pb-[16px]" : ""}`}>
      <RcSlider
        className={`Custom-RcSlider-CLSName`}
        {...SliderConfig}
        handleStyle={
          sliderValue === 0
            ? {
                ...SliderConfig.handleStyleWithInitValue
              }
            : {
                ...SliderConfig.handleStyle
              }
        }
        handleRender={handle}
        value={sliderValue}
        onBeforeChange={onBeforeChange}
        onChange={onChange}
        onAfterChange={onAfterChange}
        {...props}
      />
    </div>
  );
};

Slider.defaultProps = {};

export type { SliderProps };
export default Slider;
