import React, { useContext } from 'react';
import { getTranslations } from '../../shared/utils/localization-util';
import SettingsContext from '../settings-context';
import { buildClassName } from '../../shared/utils/class-util';
import Icon from '../../shared/components/icon';

interface AmountInputProps {
  label: string;
  value: number;
  disabled?: boolean;
  min?: number;
  onChange?: (value: number) => void;
}

const AmountInput: React.FC<AmountInputProps> = ({ label, value, disabled, min, onChange }) => {
  const { language } = useContext(SettingsContext);
  const translations = getTranslations(language);

  const handleIncreaseClick: React.MouseEventHandler<HTMLButtonElement> = (event) => {
    if (onChange) {
      onChange(value + 1);
    }
  };

  const handleDecreaseClick: React.MouseEventHandler<HTMLButtonElement> = (event) => {
    if (onChange) {
      onChange(Math.max(value - 1, min ?? 0));
    }
  };

  return (
    <div className={buildClassName(['decrement-increment', disabled && 'decrement-increment--disabled'])}>
      <label className="decrement-increment__label">{label}</label>
      <div className="decrement-increment__ui">
        {!disabled && (
          <button type="button" className="button button--decrement" title={translations.INPUT.DECREASE} disabled={disabled} onClick={handleDecreaseClick}>
            <Icon name="ui-min" />
          </button>
        )}
        <span>{value}</span>
        {!disabled && (
          <button type="button" className="button button--increment" title={translations.INPUT.INCREASE} disabled={disabled} onClick={handleIncreaseClick}>
            <Icon name="ui-plus" />
          </button>
        )}
      </div>
    </div>
  );
};

export default AmountInput;
