import { FC, useEffect, useState } from 'react';
import { Button, ButtonGroup, Input } from '@material-ui/core';
import { styled } from '@material-ui/core/styles';
import { FormFieldProps } from 'mystique/registry/FieldRegistry';
import { BiMinus, BiPlus } from 'react-icons/bi';

const MyButton = styled(Button)({
  background: 'white',
  width: '30px',
  height: '30px',
  fontSize: '16px',
  fontWeight: 'bold',
  border: '1px solid #d4d6d8',
  color: '#00a9e0',
  outline: 'none',
  '&:hover': {
    cursor: 'pointer',
    background: '#effbff',
  },
  '&.MuiInputBase-root.Mui-disabled': {
    color: ' #d4d6d8',
    background: 'transparent',
    cursor: 'default',
  },
  flex: '0.35',
});

const Counter = styled(Button)({
  background: 'white',
  width: '30px',
  height: '30px',
  fontSize: '16px',
  fontWeight: 'bold',
  border: '1px solid #d4d6d8',
  color: 'black',
  outline: 'none',
  padding: 0,
  flex: '0.3',
});

const MyInput = styled(Input)({
  background: 'transparent',
  padding: 0,
  margin: 0,
  border: 'none',
  outline: 'none',
  width: '30px',
  '& input': {
    textAlign: 'center',
  },
  '&.MuiInput-underline:before': {
    display: 'none',
  },
  '&.MuiInput-underline:after': {
    display: 'none',
  },
  '& ::-webkit-inner-spin-button': {
    appearance: 'none',
    margin: 0,
  },
  '& input[type=number]': {
    '-moz-appearance': 'textfield',
  },
});
export const QuantitySelector: FC<FormFieldProps<number>> = ({
  name,
  label,
  value,
  validation,
  onChange,
  onBlur,
}) => {
  const [count, setCount] = useState(value || 0);

  useEffect(() => {
    value !== undefined && setCount(value);
  }, [value]);

  const handleIncrement = () => {
    const newCount = count + 1;
    setCount(newCount);
    onChange(newCount);
  };

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

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    let newCount = 0;
    const inputValue = +e.target.value;
    if (inputValue < validation?.min) {
      newCount = validation?.min;
    } else if (inputValue > validation?.max) {
      newCount = validation?.max;
    } else {
      newCount = inputValue;
    }
    setCount(newCount);
    onChange(newCount);
  };

  const selectText = (
    e: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    const id = e?.target?.id;
    if (!id) return;
    const input = document.getElementById(id) as HTMLInputElement;
    input?.focus();
    input?.select();
  };

  return (
    <div>
      <div style={{ fontSize: '14px', color: 'rgba(0, 0, 0, 0.54)' }}>
        {label}
      </div>
      <ButtonGroup
        disableRipple
        size="small"
        aria-label="small outlined button group"
        style={{ fontSize: '16px', marginTop: '10px', display: 'flex' }}
      >
        <MyButton
          style={{ borderRadius: '15px 0 0 15px' }}
          disabled={count <= validation?.min}
          onClick={() => handleDecrement()}
        >
          <BiMinus />
        </MyButton>
        <Counter aria-label={label} name={name}>
          <MyInput
            id={validation?.id}
            name={name}
            value={
              validation?.id === 'quantitySelector' && validation?.max === count
                ? `All (${count})`
                : count
            }
            type={
              validation?.id === 'quantitySelector' && validation?.max === count
                ? 'text'
                : 'number'
            }
            onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
              handleChange(e)
            }
            onBlur={onBlur}
            onFocus={(
              e: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>,
            ) => selectText(e)}
          />
        </Counter>
        <MyButton
          style={{ borderRadius: '0 15px 15px 0' }}
          disabled={count >= validation?.max}
          onClick={() => handleIncrement()}
        >
          <BiPlus />
        </MyButton>
      </ButtonGroup>
    </div>
  );
};
