import React, { CSSProperties, useMemo } from 'react';
import { SilkeGradient, getCSSFromGradientModel, interceptColor } from './silke-gradient-utils';
import styles from './silke-gradient-picker.module.scss';
import { SilkeSlider } from '../silke-slider';

type SilkeGradientSliderProps = {
  value: SilkeGradient;
  selected?: number;
  onChange: (gradient: SilkeGradient) => void;
  onSelected?: (index: number) => void;
};

export function SilkeGradientSlider({
  value,
  selected,
  onChange,
  onSelected,
}: SilkeGradientSliderProps) {
  const [bg, stops] = useMemo(() => {
    const bg = getCSSFromGradientModel({ type: 'linear', pos: '90deg', stops: value.stops });
    const stops = value.stops.map((stop) => stop.position);

    return [bg, stops];
  }, [value]);

  const handleChange = (stops: number[]) => {
    const newStops = stops.map((position, i) => ({ ...value.stops[i], position }));
    onChange({ ...value, stops: newStops });
  };

  const handleRemove = (index: number): boolean => {
    const newStops = value.stops.filter((_, i) => i !== index);
    onChange({ ...value, stops: newStops });
    return true;
  };

  const handleAdd = (e: React.MouseEvent, position: number) => {
    position = Math.round(position * 100) / 100;
    const color = interceptColor(position, value.stops);
    onChange({ ...value, stops: [...value.stops, { color, position }] });
  };

  return (
    <SilkeSlider
      className={styles.slider}
      handleClassName={styles.handle}
      selected={selected}
      style={{ '--track-bg': bg } as CSSProperties}
      value={stops}
      disableOrder
      onChange={handleChange}
      onHandleClick={(e, index) => onSelected?.(index)}
      onRequestRemove={handleRemove}
      onTrackClick={handleAdd}
    />
  );
}
