import { NumberInputContainer, ButtonContainer } from "./NumberInput.styled";
import ChevronUp from "../../assets/svgs/chevron-up.svg";
import ChevronDown from "../../assets/svgs/chevron-down.svg";
import { InputProps, InputStatus } from "../..";
import { useMemo, useState } from "react";
import { gray, red, blue } from "../../../../core/colors/colors";
import { InputContainer, InputStyle } from "../../Input.styled";

export type NumberInputProps = Omit<InputProps, "type" | "onChange"> & {
  name?: string;
  onChange: (value: string, name?: string) => void;
  min?: number;
  max?: number;
  unit?: string;
  enableButton?: boolean;
};

const NumberInput = ({
  name = "",
  value,
  onChange,
  onError = () => false,
  min,
  max,
  unit,
  enableButton,
  attributes,
  placeholder,
}: NumberInputProps) => {
  const [isFocus, setIsFocus] = useState<boolean>(false);
  const status: InputStatus = useMemo(() => {
    if (onError()) return "ERROR";
    if (isFocus) return "FOCUS";
    return "DEFAULT";
  }, [isFocus, onError]);

  const style: { [key in InputStatus]: { [style in "borderColor"]: string } } =
    {
      DEFAULT: {
        borderColor: gray[300],
      },
      ERROR: {
        borderColor: red[500],
      },
      FOCUS: {
        borderColor: blue[500],
      },
    };

  const specifyMinAndMax = (name: "min" | "max") => {
    switch (name) {
      case "max":
        if (max !== undefined)
          Number(value) + 1 <= max && onChange(String(Number(value) + 1));
        else onChange(String(Number(value) + 1));
        return;
      case "min":
        if (min !== undefined)
          Number(value) - 1 >= min && onChange(String(Number(value) - 1));
        else onChange(String(Number(value) - 1));
        return;
    }
  };

  return (
    <NumberInputContainer unit={unit} enableButton={enableButton}>
      <InputContainer>
        <InputStyle
          name={name}
          type="text"
          value={value}
          onChange={(e) =>
            onChange(
              e.target.value.replace(/[^0-9]/g, ""),
              e.currentTarget.name
            )
          }
          onFocus={() => setIsFocus(true)}
          onBlur={() => setIsFocus(false)}
          onError={onError}
          {...attributes}
          placeholder={placeholder}
          style={{ ...style[status] }}
        />
      </InputContainer>
      {enableButton && (
        <ButtonContainer>
          <button onClick={() => specifyMinAndMax("max")}>
            <ChevronUp />
          </button>
          <button onClick={() => specifyMinAndMax("min")}>
            <ChevronDown />
          </button>
        </ButtonContainer>
      )}
    </NumberInputContainer>
  );
};

export default NumberInput;
