import { debounce } from 'lodash-es';
import { useEffect, useMemo, useRef, useState } from 'react';
import {
  Label,
  Slider,
  SliderOutput,
  SliderThumb,
  SliderTrack,
} from 'react-aria-components';

import { DEFAULT_CREATE_CONTROL_VALUE } from '@/utils/constants';

type Props = {
  label?: string;
  value?: number;
  onChange?: (value: number) => void;
};

// const startColor = '#65B561';
// const midpointColor = '#9FB562';
// const endColor = '#B59262';

// const getColorFromPercent = (percent: number) => {
//   if (0 <= percent && percent <= 0.5) {
//     return d3.interpolateLab(startColor, midpointColor)(percent / 0.5);
//   } else if (percent <= 1.0) {
//     return d3.interpolateLab(midpointColor, endColor)((percent - 0.5) / 0.5);
//   }
//   return 'rgb(0, 0, 0)';
// };

// const getGradientFromPercent = (percent: number) => {
//   const midpointPercent = percent / 2.0;
//   if (percent > 1 || percent < 0) {
//     return null;
//   }
//   return [
//     startColor,
//     `#${rgbHex(getColorFromPercent(midpointPercent))}`,
//     `#${rgbHex(getColorFromPercent(percent))}`,
//   ];
// };

// const getTwGradientFromPercent = (percent: number) => {
//   const gradient = getGradientFromPercent(percent);
//   if (gradient) {
//     return `bg-linear-to-r from-[${gradient[0]}] via-[${gradient[1]}] to-[${gradient[2]}]`;
//   }
//   return '';
// };

export const GradientSlider = ({ label, value, onChange }: Props) => {
  const [sliderValue, setSliderValue] = useState<number>(
    value !== undefined ? value : DEFAULT_CREATE_CONTROL_VALUE
  );
  const trackRef = useRef<any>(null);

  useEffect(() => {
    if (value !== undefined) {
      setSliderValue(value);
    }
  }, [value]);

  const handleSliderChange = useMemo(
    () =>
      debounce((val: number) => {
        onChange?.(val);
        setSliderValue(val);
      }, 300),
    [onChange]
  );

  return (
    <Slider
      defaultValue={sliderValue}
      onChange={handleSliderChange}
      className='w-full'
    >
      <div className='flex pb-1 text-sm text-foreground-primary'>
        {label ? <Label className='flex-1'>{label}</Label> : null}
        <SliderOutput />
      </div>
      <SliderTrack className='relative h-7 w-full' ref={trackRef}>
        {({ state }) => (
          <>
            {/* track */}
            <div className='absolute top-[50%] h-7 w-full translate-y-[-50%] rounded-full bg-white/40' />
            {/* fill */}
            <div
              className='absolute top-[50%] h-7 translate-y-[-50%] overflow-hidden rounded-full'
              style={{ width: state.getThumbPercent(0) * 100 + '%' }}
            >
              <div
                className={`h-7 rounded-full bg-linear-to-r from-[#65B561] via-[#B5AF62] to-[#B56762]`}
                style={{
                  width: trackRef.current
                    ? `${trackRef.current.getBoundingClientRect().width}px`
                    : '208px',
                }}
              />
            </div>
            <SliderThumb className='top-[50%] h-7 w-7 rounded-full bg-transparent ring-black transition outline-none focus-visible:ring-2 dragging:bg-transparent' />
          </>
        )}
      </SliderTrack>
    </Slider>
  );
};
