import { useState } from 'react';

import { IconMinus, IconPlus } from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';
import { type Theme } from '@material-hu/mui/index';
import Stack from '@material-hu/mui/Stack';

export type NumberInputStepperProps = {
  value?: number;
  max?: number;
  min?: number;
  onChange?: (count: number) => void;
};

const createButtonStyles = (theme: Theme, color?: string) => ({
  width: 40,
  height: 40,
  backgroundColor: theme.palette.new.background.elements.grey,
  border: 1,
  color,
  ['&:hover']: {
    color,
    border: 1,
  },
});

const NumberInputStepper = ({
  value = 0,
  max = 10,
  min = 0,
  onChange,
}: NumberInputStepperProps) => {
  const [count, setCount] = useState(value);

  const handleIncrement = () => {
    const newCount = count + 1;
    if (newCount <= max) {
      setCount(newCount);
      onChange?.(newCount);
    }
  };

  const handleDecrement = () => {
    const newCount = count - 1;
    if (newCount >= min) {
      setCount(newCount);
      onChange?.(newCount);
    }
  };

  const minusButtonColor = (theme: Theme) =>
    count === min
      ? theme.palette.new.border.neutral.default
      : theme.palette.new.border.neutral.brand;

  const plusButtonColor = (theme: Theme) =>
    count === max
      ? theme.palette.new.border.neutral.default
      : theme.palette.new.border.neutral.brand;

  return (
    <Stack sx={{ gap: 1, flexDirection: 'row' }}>
      <IconButton
        sx={theme => createButtonStyles(theme, minusButtonColor(theme))}
        onClick={handleDecrement}
      >
        <IconMinus />
      </IconButton>
      <IconButton
        sx={theme => createButtonStyles(theme, plusButtonColor(theme))}
        onClick={handleIncrement}
      >
        <IconPlus />
      </IconButton>
    </Stack>
  );
};

export default NumberInputStepper;
