import React from "react";
import { useStore } from "../stores/global-stores";

const OmsInputBarWrapper = ({ children }: { children: React.ReactNode }) => {
  return (
    <>
      <div
        className="mx-3 flex flex-nowrap items-center gap-1 my-3"
      >
        <div>
          <img src={"./images/icon-search.svg"} height={20} width={20} />
        </div>
        <div
          className="h300"
          style={{
            flex: "1",
          }}
        >
          {children}
        </div>
        <div>
          <img src={"./images/icon-cross-fill.svg"} height={20} width={20} />
        </div>
      </div>
      <hr
        color="#666666"
        style={{
          height: "1px",
          border: 0,
        }}
      />
    </>
  );
};

export default function OmsInputBar({
  query,
  updateGlobalQuery,
}: {
  query: string;
  updateGlobalQuery: (newQuery: string) => void;
}) {
  const [routes, popRoute, clearRoute] = useStore((states) => [
    states.routes,
    states.popRoute,
    states.clearRoute,
  ]);
  return (
    <OmsInputBarWrapper>
      <input
        tabIndex={0}
        autoFocus
        placeholder="Type something to search"
        id="oms-input"
        type="text"
        autoComplete="off"
        autoCorrect="off"
        autoCapitalize="off"
        spellCheck={false}
        aria-label="Spotlight input"
        value={query}
        onKeyDown={(e) => {
          console.log("[oms-input-bar] onKeyDown", e.key);
          if (e.key === "Backspace" && !query) {
            popRoute();
          } else if (e.key === "ArrowUp" || (e.key === "Tab" && e.shiftKey)) {
            (
              document.querySelector<HTMLDivElement>(".suggestion-selected")
                ?.previousElementSibling as HTMLDivElement
            )?.focus();
            e.preventDefault();
          } else if (e.key === "ArrowDown" || e.key === "Tab") {
            const selectedItem = document.querySelector<HTMLDivElement>(
              ".suggestion-selected"
            );
            if (selectedItem) {
              (selectedItem?.nextElementSibling as HTMLDivElement)?.focus();
            } else {
              document
                .querySelector<HTMLDivElement>(".suggestion-item")
                ?.focus();
              e.preventDefault(); // !important. this avoid 'tab' to jump right to 2nd suggestion from  input
            }
          } else if (e.key === "Enter") {
            document
              .querySelector<HTMLDivElement>(".suggestion-selected")
              ?.focus();
          } else if (e.key === "Tab") {
            console.log("testing", e);
          }
        }}
        onChange={(e) => {
          updateGlobalQuery(e.target.value);
        }}
      />
    </OmsInputBarWrapper>
  );
}
