import { useMemo } from "react";
import { InputStyle } from "../../Input.styled";
import { gray, red, green } from "../../../../core/colors/colors";
import { AsyncInputContainer } from "./AsyncInput.styled";
import Search from "../../assets/svgs/search.svg";
import Check from "../../assets/svgs/check.svg";
import X from "../../assets/svgs/x.svg";

export type AsyncStatus = "DEFAULT" | "LOADING" | "SUCCESS" | "ERROR";

export type AsyncInputProps = {
  value: string;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  onSearch: (value: string) => void;
  isError: () => boolean;
  isLoading: () => boolean;
  isSuccess: () => boolean;
  disable?: boolean;
  placeholder?: string;
};

const AsyncInput = ({
  value,
  onChange,
  onSearch,
  isError = () => false,
  isLoading = () => false,
  isSuccess = () => false,
  disable = false,
  placeholder,
}: AsyncInputProps) => {
  const status: AsyncStatus = useMemo(() => {
    if (isError()) return "ERROR";
    if (isLoading()) return "LOADING";
    if (isSuccess()) return "SUCCESS";
    return "DEFAULT";
  }, [isError, isLoading, isSuccess]);

  const style: { [key in AsyncStatus]: { [style in "borderColor"]: string } } =
    {
      DEFAULT: {
        borderColor: gray[300],
      },
      LOADING: {
        borderColor: gray[300],
      },
      SUCCESS: {
        borderColor: green[500],
      },
      ERROR: {
        borderColor: red[500],
      },
    };

  return (
    <AsyncInputContainer
      stroke={status === "DEFAULT" ? gray[800] : style[status].borderColor}
    >
      <InputStyle
        value={value}
        onChange={(e) => onChange(e)}
        disabled={disable}
        onKeyDown={(e) => e.key === "Enter" && onSearch(value)}
        placeholder={placeholder}
        style={{ ...style[status], paddingRight: value && "40px" }}
      />
      <article>
        {status === "DEFAULT" && (
          <button onClick={() => onSearch(value)}>
            <Search />
          </button>
        )}
        {status === "LOADING" && <div />}
        {status === "SUCCESS" && <Check />}
        {status === "ERROR" && <X />}
      </article>
    </AsyncInputContainer>
  );
};

export default AsyncInput;
