import { useEffect } from "react";
import { InputProps } from "./Input.interface";

import "./Input.scss";

const Input = ({
  name,
  placeholder,
  rules,
  value = "",
  onSetValue,
  label,
  error,
  onSetError,
  extra,
  ...props
}: InputProps) => {
  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (props.type == "number") {
      const { value, max, min } = event.target;
      if (Number(value) > Number(max)) {
        onSetValue(max);
      } else if (Number(value) > Number(min)) {
        onSetValue(value);
      } else {
        onSetValue("");
      }
    } else {
      onSetValue(event.target.value);
    }
  };

  const handleKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (props.type === "number") {
      if (!/[0-9]/.test(event.key) && event.key !== "Backspace") {
        event.preventDefault();
      }
    }
  };

  useEffect(() => {
    if (value.length > 0) {
      rules?.some((rule) => {
        if (!rule.rule(value)) {
          // console.log(value);
          onSetError?.(rule.errorMessage);
          return true;
        }
        // console.log(value);
        onSetError?.(null);

        return false;
      });
    }
  }, [onSetError, rules, value]);

  return (
    <div className={"input_container"}>
      {label}
      <div className="with_icon_container">
        <input
          className={"input"}
          name={name}
          placeholder={placeholder}
          value={value}
          onChange={handleChange}
          onKeyPress={handleKeyPress}
          {...props}
        />
        {extra}
      </div>
      {error && <div className={"error"}>{error}</div>}
    </div>
  );
};

export default Input;
