import React, { useRef, useState } from 'react';

import InputError from '../Inputs/InputError';
import styled from 'styled-components';
interface Props {
  /**
   * Aria label for error messages if applicable
   */
  ariaDescribedby?: string | undefined;
  /**
   * If the input should allow autofilling from the browser. This is not always handled properly in Chrome, so we suggest to use a string like 'nope'.
   */
  autocomplete?: string;
  /**
   * The function to run when the input loses focus/blurred.
   */
  blurCallback?: (x: string, y: object) => void;
  /**
   * A function that will run after the input  has changed, it will return the value of the input for you to use in the parent component.
   */
  callback: (x: string, y: object) => void;
  /**
   * Should the input be disabled or not. Use with a state var to determine when the input can be edited.
   */
  disabled?: boolean;
  /**
   * Pass a display method such as inline-block, inline, or bock.
   */
  display?: string;
  /**
   * An error message to be shown docked at the bottom of the input. If null, nothing will show.
   */
  error?: string;
  /**
   * An id to be added to the input itself, not the wrapping label.
   */
  id?: string;
  /**
   * Classes to be added to the input itself.
   */
  inputTheme?: string;
  /**
   * Callback when a key is released
   */
  keyUpCallback?: (x: object) => void;
  /**
   * The allowed max length of characters into the input.
   */
  maxLength?: number;
  /**
   * The allowed min lenght of characters into the input.
   */
  minLength?: number;
  /**
   * If true, will show an (optional) tag next to the title. If false or not supplied, nothing will show.
   */
  optional?: boolean;
  /**
   * Regex to match on the input.
   */
  pattern?: string;
  /**
   * Placeholder value to show on the input before any value is entered.
   */
  placeHolder?: string;
  /**
   * The default value to be populated into the input on load.
   */
  populatedValue?: string;
  /**
   * If true, will show a required *'s. If false or not supplied, nothing will show.
   */
  required?: boolean;
  /**
   * Size of the input, will effect length as how many chars will show
   */
  size?: number;
  /**
   * Classes to be added to the wrapping label.
   */
  theme?: string;
  /**
   * The label text title of the input.
   */
  title: string;
  /**
   *
   */
  type?: string;
  name?: string;
  showPasswordLink?: boolean;
  autocorrect?: string;
}

const Input = ({
  ariaDescribedby = undefined,
  autocomplete = '',
  autocorrect = '',
  blurCallback,
  callback,
  disabled = false,
  display = 'block',
  error = '',
  id,
  inputTheme,
  keyUpCallback,
  maxLength,
  minLength,
  optional = false,
  pattern,
  placeHolder,
  populatedValue,
  required = false,
  size = 50,
  theme,
  title = 'Input Name',
  type = 'text',
  name,
  showPasswordLink = false,
}: Props) => {
  const inputRef = useRef<HTMLInputElement>(null);
  const [inputType, inputTypeSetter] = useState(type);

  // useEffect(() => {
  //   if (error !== null && inputRef.current) inputRef.current.focus();
  // }, [error]);

  return (
    <span className={`margin--bottom position--relative relative ${display}`}>
      <label data-test="component-input" className={`nwc--input ${theme}`} htmlFor={id}>
        {title && (
          <div className="nwc--label-wrap">
            <strong className="font--14 font--dark">
              <span data-test="component-input-title">{title}</span>
              {required === true && (
                <sup data-test="component-input-required" className="font--error font--10">
                  {' *'}
                </sup>
              )}
              {optional === true && (
                <sup data-test="component-input-optional" className="font--grey font--10">
                  {' (optional)'}
                </sup>
              )}
            </strong>
          </div>
        )}
        <input
          ref={inputRef}
          data-test="component-input-input"
          autoComplete={autocomplete}
          autoCorrect={autocorrect}
          className={`border ${inputTheme}`}
          defaultValue={populatedValue}
          disabled={disabled}
          id={id}
          maxLength={maxLength}
          minLength={minLength}
          name={name ?? id}
          onBlur={(e) => blurCallback && blurCallback(e.target.value, e)}
          onChange={(e) => callback && callback(e.target.value, e)}
          onKeyUp={(e) => keyUpCallback && keyUpCallback(e)}
          pattern={pattern}
          placeholder={placeHolder}
          size={size}
          type={inputType}
          aria-invalid={error !== null}
          aria-describedby={ariaDescribedby}
          required={required}
        />

        {type === 'password' && showPasswordLink && (
          <ShowPassword type="button" className=" background--none border--none" onClick={() => inputTypeSetter(inputType === 'password' ? 'text' : 'password')}>{`${
            inputType === 'password' ? 'Show' : 'Hide'
          } Password`}</ShowPassword>
        )}
        {error !== '' && error !== null && <InputError error={error} id={id} />}
      </label>
    </span>
  );
};

export default Input;
const ShowPassword = styled.button`
  font-size: 12px;
  display: flex;
  flex-direction: column;
  margin-bottom: 5px;
  margin-left: auto;
  padding-top: 5px;
  float: right;
  border-bottom: 1px dotted rgb(0, 0, 0) !important;
`;
