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

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

export function Darkens({ color, darkens, mix, step, maximum, copyMode }: DarkensProps) {
  const { colorFn } = useColorFunction();
  const colors = useMemo(() => {
    try {
      if (!colorFn) {
        return Array.from({ length: darkens + 1 }, () => color);
      }
      const darkenColors = [color];
      switch (mix) {
        case 'progressive':
          for (let i = 1; i <= darkens; i++) {
            const darkenColor = colorFn.darken(last(darkenColors), step);
            darkenColors.push(darkenColor);
          }
          break;
        case 'linear':
          for (let i = 1; i <= darkens; i++) {
            const darkenColor = colorFn.darken(color, step * i);
            darkenColors.push(darkenColor);
          }
          break;
        case 'average': {
          const interval = maximum / darkens / 100;
          for (let i = 1; i <= darkens; i++) {
            const darkenColor = colorFn.darken(color, interval * i);
            darkenColors.push(darkenColor);
          }
          break;
        }
      }
      return darkenColors.reverse();
    } catch (e) {
      console.error('[Generate Lighten]', e);
    }
    return Array.from({ length: darkens + 1 }, () => color);
  }, [color, darkens, mix, step, maximum]);

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