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

export interface IQuantitySelectorProps {
  maxQuantity: number;
  initialQuantity?: number;
  title?: string;
  onConfirm: (quantity: number) => void;
  onClose: () => void;
}

export const QuantitySelector: React.FC<IQuantitySelectorProps> = ({
  maxQuantity,
  initialQuantity,
  title = 'Select quantity',
  onConfirm,
  onClose,
}) => {
  const [value, setValue] = useState(initialQuantity ?? maxQuantity);
  const inputRef = useRef<HTMLInputElement>(null);

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

    if (inputRef.current) {
      inputRef.current.focus();
      inputRef.current.select();
    }

    document.addEventListener('keydown', closeSelector);
    return () => document.removeEventListener('keydown', closeSelector);
  }, [onClose]);

  return (
    <StyledContainer type={RPGUIContainerTypes.Framed} width="25rem">
      <CloseButton className="container-close" onPointerDown={onClose}>
        X
      </CloseButton>
      <h2>{title}</h2>
      <StyledForm
        onSubmit={e => {
          e.preventDefault();
          const numberValue = Number(value);
          if (!Number.isNaN(numberValue)) {
            onConfirm(Math.max(1, Math.min(maxQuantity, numberValue)));
          }
        }}
        noValidate
      >
        <StyledInput
          ref={inputRef}
          placeholder="Enter quantity"
          type="number"
          min={1}
          max={maxQuantity}
          value={value}
          onChange={e => {
            if (Number(e.target.value) >= maxQuantity) {
              setValue(maxQuantity);
              return;
            }
            setValue(Number(e.target.value));
          }}
          onBlur={e => {
            setValue(
              Math.max(1, Math.min(maxQuantity, Number(e.target.value)))
            );
          }}
        />
        <RangeSlider
          type={RangeSliderType.Slider}
          valueMin={1}
          valueMax={maxQuantity}
          width="100%"
          onChange={setValue}
          value={value}
        />
        <Button buttonType={ButtonTypes.RPGUIButton} type="submit">
          Confirm
        </Button>
      </StyledForm>
    </StyledContainer>
  );
};

const StyledContainer = styled(RPGUIContainer)`
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 1rem;

  h2 {
    margin: 0;
    margin-bottom: 1rem;
    font-size: 1rem;
  }
`;

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

const StyledForm = styled.form`
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
  width: 100%;
`;

const StyledInput = styled.input`
  width: 100%;
  padding: 0.5rem;
  background-color: rgba(0, 0, 0, 0.25);
  border: none;
  color: white;
  font-size: 1rem;
  text-align: center;

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

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