import { ChangeEvent, HTMLAttributes, InputHTMLAttributes, useState } from "react";

import "./Input.css";
import { getCN, randomId, usePadding, renderProps } from "../utils";

import FormField, { IFormField } from "../../componentsDefault/FormField/FormField";

export interface IInput extends InputHTMLAttributes<HTMLInputElement> {
  before?: IFormField["before"];
  after?: IFormField["after"];
  status?: IFormField["status"];
  top?: IFormField["top"];
  bottom?: IFormField["bottom"];
  type?: "text" | "password" | "email" | "tel" | "number" | "hidden";
}

function Input({
  type = `text`,
  before,
  after,
  status,
  top,
  bottom,
  maxLength,
  value,
  onChange,
  ...props
}: IInput) {
  const [props_id, setPropsId] = useState(randomId(props.id, `input_text`));

  const hanldeChange = (e: ChangeEvent<HTMLInputElement>) => {
    if (Number(maxLength) && maxLength) {
      e.target.value = cleanString(String(e.target.value), maxLength);
      if (onChange) onChange(e)
    } else {
      if (onChange) onChange(e)
    }
  }

  return (
    <FormField
      before={before}
      after={after}
      status={status}
      top={top}
      bottom={bottom}
      {...props}
      hovered={`input`}
      formClassName={getCN([
        `Input`,
        !before && after && "MYUI-FormField__in--after",
        before && !after && "MYUI-FormField__in--before",
        after && before && "MYUI-FormField__in--before_after",
      ])}
    >
      <input
        aria-label={props_id}
        id={props_id}
        value={value}
        onChange={hanldeChange}
        {...renderProps(props)}
        type={type}
      />
    </FormField>
  );
}

const cleanString = (input: string, maxLength: number) => {
  var output = "";
  for (var i = 0; i < input.length; i++) {
    if (output.length < maxLength) {
      output += input[i];
    }
  }
  return output;
}

export default Input;
