import React, { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { Button, ButtonTypes } from '../../Button';
import { Input } from '../../Input';
import {
  RPGUIContainer,
  RPGUIContainerTypes,
} from '../../RPGUI/RPGUIContainer';
import { RangeSlider, RangeSliderType } from '../../RangeSlider';

export interface IItemQuantitySelectorProps {
  quantity: number;
  onConfirm: (quantity: number) => void;
  onClose: () => void;
}

export const ItemQuantitySelector: React.FC<IItemQuantitySelectorProps> = ({
  quantity,
  onConfirm,
  onClose,
}) => {
  const [value, setValue] = useState(quantity);

  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus();
      inputRef.current.select();

      const closeSelector = (e: KeyboardEvent) => {
        if (e.key === 'Escape') {
          onClose();
        }
      };

      document.addEventListener('keydown', closeSelector);

      return () => {
        document.removeEventListener('keydown', closeSelector);
      };
    }

    return () => {};
  }, []);

  return (
    <StyledContainer type={RPGUIContainerTypes.Framed} width="25rem">
      <CloseButton className="container-close" onPointerDown={onClose}>
        X
      </CloseButton>
      <h2>Select quantity to move</h2>
      <StyledForm
        style={{ width: '100%' }}
        onSubmit={e => {
          e.preventDefault();

          const numberValue = Number(value);

          if (Number.isNaN(numberValue)) {
            return;
          }

          onConfirm(Math.max(1, Math.min(quantity, numberValue)));
        }}
        noValidate
      >
        <StyledInput
          innerRef={inputRef}
          placeholder="Enter quantity"
          type="number"
          min={1}
          max={quantity}
          value={value}
          onChange={e => {
            if (Number(e.target.value) >= quantity) {
              setValue(quantity);
              return;
            }

            setValue((e.target.value as unknown) as number);
          }}
          onBlur={e => {
            const newValue = Math.max(
              1,
              Math.min(quantity, Number(e.target.value))
            );

            setValue(newValue);
          }}
        />
        <RangeSlider
          type={RangeSliderType.Slider}
          valueMin={1}
          valueMax={quantity}
          width="100%"
          onChange={setValue}
          value={value}
        />
        <Button buttonType={ButtonTypes.RPGUIButton} type="submit">
          Confirm
        </Button>
      </StyledForm>
    </StyledContainer>
  );
};

const StyledContainer = styled(RPGUIContainer)`
  display: flex;
  flex-direction: column;
  align-items: center;
`;

const StyledForm = styled.form`
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
`;
const StyledInput = styled(Input)`
  text-align: center;

  &::-webkit-outer-spin-button,
  &::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }

  &[type='number'] {
    -moz-appearance: textfield;
  }
`;

const CloseButton = styled.div`
  position: absolute;
  top: 3px;
  right: 0px;
  color: white;
  z-index: 22;
  font-size: 0.8rem;
`;
