import React, { useEffect, useState } from "react";
//icons
import ArrowLight from "../../assets/icons/arrowLight.svg";
import ArrowDark from "../../assets/icons/arrowDark.svg";
import CloseIconLight from "../../assets/icons/xCircleLight.svg";
import CloseIconDark from "../../assets/icons/xCircleDark.svg";
import CleanIconLight from "../../assets/icons/xCircleOutlinedLight.svg";
import CleanIconDark from "../../assets/icons/xCircleOutlinedDark.svg";

import styles from "./TextInput.module.scss";

import Image from "next/image";

type TextInputT = {
  id: string;
  handleChange: (va: string) => void;
  handleCleanValues?: () => void;
  theme?: "light" | "dark";
  placeholder?: string;
  title: string;
  devalultValue?: string;
  errorText?: string;
  showCleanButton?: boolean;
  isNumeric?: boolean;
};

const TextInput = (props: TextInputT) => {
  const {
    id,
    handleChange,
    theme = "light",
    placeholder = "Enter the value",
    title,
    devalultValue = "",
    errorText,
    showCleanButton,
    handleCleanValues,
    isNumeric,
  } = props;

  const [inputValue, setInputValue] = useState<string>(devalultValue);

  useEffect(() => {
    if (inputValue !== undefined) {
      handleChange(inputValue);
    }
  }, [inputValue]);

  const onCleanHandler = () => {
    handleCleanValues && handleCleanValues();
    setInputValue("");
  };

  const handleKeyPress = (event: React.KeyboardEvent) => {
    if (isNumeric) {
      const keyCode = event.keyCode || event.which;
      const keyValue = String.fromCharCode(keyCode);
      if (!/^\d+$/.test(keyValue)) {
        event.preventDefault();
      }
    }
  };

  return (
    <div
      className={
        theme === "light"
          ? styles.light_text_input_wrapper
          : styles.dark_text_input_wrapper
      }
    >
      <p
        className={
          theme === "light"
            ? styles.text_input_title
            : styles.text_input_title_dark
        }
      >
        {title}
      </p>
      <input
        value={inputValue}
        type={"text"}
        className={
          errorText
            ? `${styles.error_text_input} ${styles.text_input}`
            : styles.text_input
        }
        data-id={id}
        placeholder={placeholder}
        onChange={(e) => {
          setInputValue(e.target.value);
        }}
        onKeyPress={handleKeyPress}
      />
      {errorText ? <p className={styles.error_text}>{errorText}</p> : null}
      {showCleanButton && (
        <div className={styles.clean_button} onClick={onCleanHandler}>
          <Image
            alt="Clean icon"
            src={theme === "dark" ? CleanIconDark : CleanIconLight}
          />
        </div>
      )}
    </div>
  );
};

export default TextInput;
