import React from 'react';

import type { HsvaColor } from '@/mui/helpers/color';
import { clamp, hsvaToHslString, round } from '@/mui/helpers/color';

import Interactive, { InteractionProps } from '../Interactive/Interactive';

import styles from './SaturationControl.module.scss';

type Props = {
  hsva: HsvaColor;
  onChange: (newColor: { s: number; v: number }) => void;
};

function SaturationControl({ hsva, onChange }: Props) {
  const backgroundColor = hsvaToHslString({
    h: hsva.h,
    s: 100,
    v: 100,
    a: 1,
  });

  return (
    <Interactive
      className={styles.Saturation}
      saturation
      style={
        {
          backgroundColor,
          '--internal-pointer-left': `${hsva.s}%`,
          '--internal-pointer-top': `${100 - hsva.v}%`,
          '--internal-pointer-color': hsvaToHslString(hsva),
        } as React.CSSProperties
      }
      onMove={(interaction: InteractionProps) => {
        onChange({
          s: interaction.left * 100,
          v: 100 - interaction.top * 100,
        });
      }}
      onKey={(offset: InteractionProps) => {
        onChange({
          s: clamp(hsva.s + offset.left * 100, 0, 100),
          v: clamp(hsva.v - offset.top * 100, 0, 100),
        });
      }}
      aria-label="Color"
      aria-valuetext={`Saturation ${round(hsva.s)}%, Brightness ${round(hsva.v)}%`}
    />
  );
}

export default React.memo(SaturationControl);
