import { InputHTMLAttributes, useMemo, useState } from "react";
import { InputContainer, InputStyle, InputXButton } from "./Input.styled";
import { gray, red, primary } from "../../core/colors/colors";
import X from "../../assets/svgs/x.svg";

export type InputStatus = "DEFAULT" | "ERROR" | "FOCUS";

export type InputProps = {
  type?: "date" | "number" | "text" | "password";
  name?: string;
  value: string;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  onError?: () => boolean;
  onReset?: () => void;
  disable?: boolean;
  enableButton?: boolean;
  attributes?: InputHTMLAttributes<HTMLInputElement>;
  placeholder?: string;
};

const Input = ({
  type = "text",
  name,
  value,
  onChange,
  onError = () => false,
  onReset,
  disable = false,
  enableButton = true,
  attributes,
  placeholder,
}: InputProps) => {
  const [isFocus, setIsFocus] = useState<boolean>(false);
  const status: InputStatus = useMemo(() => {
    if (onError()) return "ERROR";
    if (isFocus) return "FOCUS";
    return "DEFAULT";
  }, [isFocus, onError]);

  const style: { [key in InputStatus]: { [style in "borderColor"]: string } } =
    {
      DEFAULT: {
        borderColor: gray[300],
      },
      ERROR: {
        borderColor: red[500],
      },
      FOCUS: {
        borderColor: primary[500],
      },
    };

  return (
    <InputContainer>
      <InputStyle
        type={type}
        name={name}
        value={value}
        onChange={(e) => onChange(e)}
        onFocus={() => setIsFocus(true)}
        onBlur={() => setIsFocus(false)}
        disabled={disable}
        {...attributes}
        placeholder={placeholder}
        style={{
          ...style[status],
          paddingRight: enableButton ? value && "40px" : "15px",
        }}
      />
      {enableButton && ((value && !disable) || onError()) && (
        <InputXButton
          onClick={() => {
            setIsFocus(false);
            onReset && onReset();
          }}
        >
          <X />
        </InputXButton>
      )}
    </InputContainer>
  );
};

export default Input;
