import React from "react";
import { Input as AntdInput, InputNumber } from "antd";
import Label from "../Label/Label";
import styled from "styled-components";
import HelperText from "../HelperText/HelperText";

const StyledContainer = styled.div`
  width: 100%;
`;

const inputTypes = {
  search: "search",
  password: "password",
  otp: "otp",
  textarea: "textarea",
  number: "number",
};

const getInputBox = (inputType) => {
  if (inputType === inputTypes.search) return AntdInput.Search;
  if (inputType === inputTypes.password) return AntdInput.Password;
  if (inputType === inputTypes.otp) return AntdInput.OTP;
  if (inputType === inputTypes.textarea) return AntdInput.TextArea;
  if (inputType === inputTypes.number) return InputNumber;
  return AntdInput;
};

const withStyledInputBox = (InputBox, inputType) => styled(InputBox)`
  width: 100%;
  color: #2f4644;
  padding-left: ${inputType === inputTypes.search ? "initial" : inputType === inputTypes.number ? "1px" : "12px"};
`;

// Create a memoized styled component factory
const createStyledInputBox = (inputType) => {
  const InputBox = getInputBox(inputType);
  return withStyledInputBox(InputBox, inputType);
};

// Store styled components in a map to avoid recreating them
const StyledInputBoxes = {
  search: createStyledInputBox(inputTypes.search),
  password: createStyledInputBox(inputTypes.password),
  otp: createStyledInputBox(inputTypes.otp),
  textarea: createStyledInputBox(inputTypes.textarea),
  number: createStyledInputBox(inputTypes.number),
  default: createStyledInputBox(),
};

const Input = (props) => {
  const {
    label,
    size,
    placeholder,
    status,
    error,
    helperText,
    required,
    className,
    inputType = "default",
    inputRef,
    ...rest
  } = props;

  const StyledInputBox = StyledInputBoxes[inputType] || StyledInputBoxes.default;

  return (
    <StyledContainer className="veris-input-container">
      {label && <Label className="veris-input-label" label={label} required={required} />}
      <StyledInputBox
        className={className}
        size={size}
        placeholder={placeholder}
        status={status ? status : error ? "error" : ""}
        ref={inputRef}
        {...rest}
      />
      {helperText && (
        <HelperText error={error || status === "error"}>
          {helperText ? helperText : typeof error === "string" ? error : ""}
        </HelperText>
      )}
    </StyledContainer>
  );
};

export default Input;
