import * as React from "react";
import "./style.css";
import isAlphabetical from "./alphabetical";
import isNumerical from "./numeric";
import * as errors from "./errors";

type PropType = {
  label: string;
  types?: ValidationTypes[];
};

type StateType = {
  invalid: boolean;
  error: string;
};

export enum ValidationTypes {
  NumericalsOnly,
  AlphabetOnly
}

const initialState = {
  invalid: false,
  error: ""
};

class FieldWithValidation extends React.Component<PropType, StateType> {
  element: HTMLInputElement;
  constructor(props: PropType) {
    super(props);
    this.state = initialState;
  }
  validateFields(e: React.FormEvent<HTMLInputElement>) {
    const el = e.target as HTMLInputElement;
    const invalid = !el.validity.valid;
    let error = el.validationMessage;
    if (!invalid) {
      error = this.checkOther(el.value);
    }
    /* else if (el.validationMessage !== this.state.error) {
      this.throwError(el.validationMessage);
    } */
    console.log("last error:", error);
    if (error) {
      this.throwError(error);
    } else if (!error && this.state.invalid) {
      console.log("went in to clear errors");
      this.clearError();
    }
    return true;
  }
  checkOther(value: any) {
    console.log("checking other");
    const { types } = this.props;
    let error = "";
    types.forEach(type => {
      switch (type) {
        case ValidationTypes.NumericalsOnly:
          error = !isNumerical(value) && errors.NumericalsOnly;
          break;
        case ValidationTypes.AlphabetOnly:
          error = !isAlphabetical(value) && errors.AlphabetOnly;
      }
    });
    console.log("other error:", error);

    return error;
  }
  throwError(error: string) {
    this.setState({ error, invalid: true });
    console.log("throwing error, set the stated");

    return false;
  }
  clearError() {
    console.log("clearing error");
    this.setState(initialState);
  }
  render() {
    const { label, ...props } = this.props;
    const { invalid } = this.state;

    return (
      <div className={`singleField ${invalid ? "invalid" : "valid"}`}>
        <label>{label}</label>
        <input
          {...props}
          ref={el => {
            this.element = el;
          }}
          onBlur={e => {
            this.validateFields(e);
          }}
        />
        {this.state.error}
      </div>
    );
  }
}

export default FieldWithValidation;
