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

import classNames from "classnames";

import Spotlight from "@enact/spotlight";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";

import TButton from "../../../components/TButton/TButton";
import TIconButton, {
  ICON_TYPES,
} from "../../../components/TIconButton/TIconButton";
import css from "./RecommendedKeywords.module.less";

const Container = SpotlightContainerDecorator(
  { enterTo: "last-focused" },
  "div"
);
const ContainerBasic = SpotlightContainerDecorator(
  { enterTo: "last-focused" },
  "div"
);

export default function RecommendedKeywords({
  keywords,
  onPrev,
  onNext,
  hasPrevPage,
  hasNextPage,
  handleSearchSubmit,
  isRecommendedSearchRef,
}) {
  const onKeyDownNext = (e) => {
    if (e.key === "ArrowRight" || e.key === "Right") {
      onNext();
      e.stopPropagation();
    }
  };
  const onKeyDownPrev = (e) => {
    if (e.key === "ArrowLeft" || e.key === "Left") {
      onPrev();
      e.stopPropagation();
    }
  };

  const _handleSearchSubmit = useCallback(
    (searchQuery) => () => {
      if (handleSearchSubmit) {
        handleSearchSubmit(searchQuery);
        isRecommendedSearchRef.current = true;
      }
    },
    [handleSearchSubmit, isRecommendedSearchRef]
  );

  return (
    <ContainerBasic className={css.container}>
      {hasPrevPage && (
        <TIconButton
          iconType={ICON_TYPES.leftArrow}
          className={classNames(css.arrow, css.arrowLeft)}
          onClick={onPrev}
          onKeyDown={onKeyDownPrev}
          ariaLabel="Move to left"
        />
      )}
      <Container className={css.keywordsGrid}>
        {keywords.map((keyword, index) => (
          <TButton
            key={index}
            spotlightId={index === 0 ? "first-keyword-button" : undefined}
            className={classNames(css.keywordBox)}
            onClick={_handleSearchSubmit(keyword.keywd)}
            ariaLabel={`"` + keyword.keywd + `", search this keyword`}
          >
            {keyword.keywd}
          </TButton>
        ))}
      </Container>
      {hasNextPage && (
        <TIconButton
          iconType={ICON_TYPES.rightArrow}
          className={classNames(css.arrow, css.arrowRight)}
          onClick={onNext}
          onKeyDown={onKeyDownNext}
          ariaLabel="Move to right"
        />
      )}
    </ContainerBasic>
  );
}
