import React from 'react';
import styled from 'styled-components';
import ModalPortal from '../Abstractions/ModalPortal';
import { QuantitySelector } from './QuantitySelector';

export interface IQuantitySelect {
  isOpen: boolean;
  maxQuantity: number;
  callback: (quantity: number) => void;
  title?: string;
  initialQuantity?: number;
}

interface IProps {
  quantitySelect: IQuantitySelect;
  setQuantitySelect: React.Dispatch<React.SetStateAction<IQuantitySelect>>;
}

const validateQuantitySelect = (
  quantitySelect: IQuantitySelect
): IQuantitySelect => ({
  ...quantitySelect,
  maxQuantity: Math.max(1, quantitySelect.maxQuantity),
  initialQuantity: quantitySelect.initialQuantity
    ? Math.max(
        1,
        Math.min(quantitySelect.maxQuantity, quantitySelect.initialQuantity)
      )
    : undefined,
});

export const QuantitySelectorModal = ({
  quantitySelect,
  setQuantitySelect,
}: IProps): JSX.Element => {
  const resetQuantitySelect = () => {
    setQuantitySelect({
      isOpen: false,
      maxQuantity: 1,
      callback: () => {},
    });
  };

  // Validate the input values
  const validatedQuantitySelect = validateQuantitySelect(quantitySelect);

  return (
    <ModalPortal>
      <QuantitySelectorContainer>
        <QuantitySelector
          maxQuantity={validatedQuantitySelect.maxQuantity}
          initialQuantity={validatedQuantitySelect.initialQuantity}
          title={validatedQuantitySelect.title}
          onConfirm={quantity => {
            validatedQuantitySelect.callback(quantity);
            resetQuantitySelect();
          }}
          onClose={() => {
            validatedQuantitySelect.callback(-1);
            resetQuantitySelect();
          }}
        />
      </QuantitySelectorContainer>
    </ModalPortal>
  );
};

const QuantitySelectorContainer = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 100;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
`;
