import React, { useCallback, useState } from "react";

import classNames from "classnames";

import { InputField } from "@enact/sandstone/Input";
import Spotlight from "@enact/spotlight";
import Spottable from "@enact/spotlight/Spottable";

import useScrollReset from "../../hooks/useScrollReset";
import TIconButton from "../TIconButton/TIconButton";
import css from "./TInput.module.less";

const KINDS = { withIcon: "withIcon" };
const ICONS = { search: "search" };
const BORDER = { none: "none" };
const COLOR = { transparent: "transparent" };

const Container = Spottable("div");
export default function TInput({
  kind,
  icon,
  border,
  color,
  className,
  spotlightDisabled,
  spotlightBoxDisabled,
  spotlightId,
  disabled,
  onKeyDown,
  scrollTop,
  onIconClick,
  forcedSpotlight,
  ...rest
}) {
  const { handleScrollReset, handleStopScrolling } = useScrollReset(scrollTop);
  const handleContainerClick = useCallback((e) => {
    if (e.key === "ArrrowLeft" || e.key === "Left") {
      Spotlight.focus("spotlight_search");
    } else {
      Spotlight.focus("input-field-box");
    }
  }, []);

  const handleButtonKeyDown = useCallback((e) => {
    if (e.key === "ArrowDown" || e.key === "Down") {
      Spotlight.move("down");
    }

    if (e.key === "ArrowLeft" || e.key === "Left") {
      e.preventDefault();
      e.stopPropagation();
      Spotlight.focus("input-field-box");
    }
  }, []);

  const handleBoxKeyDown = useCallback((e) => {
    if (e.key === "ArrowLeft" || e.key === "Left") {
      const currentElement = e.currentTarget;
      const inputElement = currentElement.querySelector("input");

      if (inputElement.value.length === 0) {
        e.preventDefault();
        e.stopPropagation();
        Spotlight.focus("spotlight_search");
      }
    }
  }, []);

  return (
    <Container
      className={classNames(css.container, className ? className : null)}
      spotlightId={spotlightId}
      onClick={handleContainerClick}
      onKeyDown={handleBoxKeyDown}
    >
      <InputField
        {...rest}
        spotlightDisabled={spotlightDisabled}
        className={classNames(css.input)}
        autoFocus
        onFocus={handleScrollReset}
        onBlur={handleStopScrolling}
        onKeyDown={onKeyDown}
        spotlightId={"input-field-box"}
        aria-label="Keyword edit box"
        dismissOnEnter
      />

      {kind === "withIcon" && (
        <TIconButton
          className={classNames(icon && css[icon])}
          onClick={onIconClick}
          forcedSpotlight={forcedSpotlight}
          ariaLabel="Search, button"
          onKeyDown={handleButtonKeyDown}
        />
      )}
    </Container>
  );
}

export { BORDER, COLOR, ICONS, KINDS };
