import React from 'react';

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

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

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

type Props = {
  hsva: HsvaColor;
  onChange: (newAlpha: { a: number }) => void;
};

function AlphaControl({ hsva, onChange }: Props) {
  const ariaValue = round(hsva.a * 100);

  return (
    <Interactive
      className={styles.Alpha}
      style={
        {
          '--internal-color-from': hsvaToHslaString({ ...hsva, a: 0 }),
          '--internal-color-to': hsvaToHslaString({ ...hsva, a: 1 }),
          '--internal-pointer-left': `${hsva.a * 100}%`,
          '--internal-pointer-top': '50%',
          '--internal-pointer-color': hsvaToHslaString(hsva),
        } as React.CSSProperties
      }
      onMove={(interaction: InteractionProps) => {
        onChange({ a: interaction.left });
      }}
      onKey={(offset: InteractionProps) => {
        onChange({ a: clamp(hsva.a + offset.left) });
      }}
      aria-label="Alpha"
      aria-valuetext={`${ariaValue}%`}
      aria-valuenow={ariaValue}
      aria-valuemin="0"
      aria-valuemax="100"
    />
  );
}

export default React.memo(AlphaControl);
