import { Title } from "./Title";
import { Slider } from "antd";
import { useEffect, useState } from "react";

const Mark = ({ value }) => {
  return <span className={"text-grey text-xs"}>{value}</span>;
};

const getInitialMarks = (fullRange, value) => {
  if (Array.isArray(value)) {
    const [min, max] = value;
    return {
      ...fullRange,
      [min]: <Mark value={min} />,
      [max]: <Mark value={max} />,
    };
  } else {
    return {
      ...fullRange,
      [value]: <Mark value={value} />,
    };
  }
};

export const SliderComponent = ({
  title,
  value: initialValue,
  onChange,
  onAfterChange,
  min = 0,
  max = 100,
  range = false,
  step = 1,
  disabled = false,
  onMouseEnter,
  onMouseLeave,
  showZeroMark = false,
}) => {
  const fullRangeMarks = {
    [min]: <Mark value={min} />,
    [max]: <Mark value={max} />,
  };
  const [value, setValue] = useState(initialValue);
  const [marks, setMarks] = useState(
    getInitialMarks(fullRangeMarks, initialValue)
  );

  useEffect(() => {
    setValue(initialValue);
    setMarks(getInitialMarks(fullRangeMarks, initialValue));
  }, [initialValue]);

  const handleAfterChange = (value) => {
    if (Array.isArray(value)) {
      const [min, max] = value;
      setMarks({
        ...fullRangeMarks,
        [min]: <Mark value={min} />,
        [max]: <Mark value={max} />,
      });
    } else {
      setMarks({
        ...fullRangeMarks,
        [value]: <Mark value={value} />,
      });
    }

    onAfterChange?.(value);
  };

  const handleChange = (value) => {
    setValue(value);
    onChange?.(value);
  };

  const finalMarks = showZeroMark ? { ...marks, 0: <Mark value={0} /> } : marks;

  return (
    <div onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>
      <Title text={title} />
      <Slider
        range={range}
        value={value}
        marks={finalMarks}
        onChange={handleChange}
        onAfterChange={handleAfterChange}
        min={min}
        max={max}
        step={step}
        disabled={disabled}
      />
    </div>
  );
};
