import { last } from 'lodash-es';
import { useMemo } from 'react';
import { useColorFunction } from '../../ColorFunctionContext';
import { FlexColorStand } from '../../components/FlexColorStand';

type LightensProps = {
  color: string;
  lightens: number;
  mix: 'progressive' | 'linear' | 'average';
  step?: number;
  maximum?: number;
  copyMode: 'hex' | 'rgb' | 'hsl' | 'lab' | 'oklch';
};

export function Lightens({ color, lightens, mix, step, maximum, copyMode }: LightensProps) {
  const { colorFn } = useColorFunction();
  const colors = useMemo(() => {
    try {
      if (!colorFn) {
        return Array.from({ length: lightens + 1 }, () => color);
      }
      const lightenColors = [color];
      switch (mix) {
        case 'progressive':
          for (let i = 1; i <= lightens; i++) {
            const lightenColor = colorFn.lighten(last(lightenColors) ?? '', step ?? 0);
            lightenColors.push(lightenColor);
          }
          break;
        case 'linear':
          for (let i = 1; i <= lightens; i++) {
            const lightenColor = colorFn.lighten(color, (step ?? 0) * i);
            lightenColors.push(lightenColor);
          }
          break;
        case 'average': {
          const interval = (maximum ?? 0) / lightens / 100;
          for (let i = 1; i <= lightens; i++) {
            const lightenColor = colorFn.lighten(color, interval * i);
            lightenColors.push(lightenColor);
          }
          break;
        }
      }
      return lightenColors;
    } catch (e) {
      console.error('[Generate Lighten]', e);
    }
    return Array.from({ length: lightens + 1 }, () => color);
  }, [color, lightens, mix, step, maximum]);

  return (
    <>
      {colors.map((c, index) => (
        <FlexColorStand key={`${c}-${index}`} color={c} valueMode={copyMode} />
      ))}
    </>
  );
}
