import React, { memo, useEffect, useMemo, useRef } from "react";

import { useDispatch, useSelector } from "react-redux";

import { Job } from "@enact/core/util";
import Spotlight from "@enact/spotlight";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";

import { sendLogSearch } from "../../../actions/logActions";
import { $L } from "../../../utils/helperMethods";
import { SpotlightIds } from "../../../utils/SpotlightIds";
import css from "./SearchResults.module.less";
import SearchResultsType from "./SearchResultsType";

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

export default memo(function SearchResults({
  isRecommendedSearchRef,
  panelInfo,
  searchQueryRef,
}) {
  const dispatch = useDispatch();
  const searchDatas = useSelector((state) => state.search.searchDatas) || {};
  const totalCount = useSelector((state) => state.search.totalCount) || {};
  const searchTimestamp = useSelector((state) => state.search.searchTimestamp);

  const results = useMemo(() => {
    const ret = Object.entries(searchDatas).reduce((acc, [key, data]) => {
      if (!data) return acc;

      const titleMap = {
        theme: $L("Hot Picks"),
        show: $L("Shows"),
        item: $L("Items"),
      };

      const item = {
        title: titleMap[key],
        category: key,
        count: totalCount[key],
        data,
      };
      acc.push(item);
      return acc;
    }, []);
    return ret;
  }, [searchDatas, totalCount]);

  useEffect(() => {
    if (!panelInfo.currentSpot) {
      if (searchDatas) {
        Spotlight.focus("search-result-type");
      }
    }
  }, [searchDatas, searchTimestamp]);

  useEffect(() => {
    if (Object.keys(totalCount).length > 0 && searchQueryRef.current) {
      const { item = 0, show = 0, theme = 0 } = totalCount;

      const params = {
        inputFlag: isRecommendedSearchRef.current ? "keyword" : "input",
        itemCnt: `${item}`,
        keyword: searchQueryRef.current,
        showCnt: `${show}`,
        themeCnt: `${theme}`,
      };

      dispatch(sendLogSearch(params));
      isRecommendedSearchRef.current = false;
    }
  }, [totalCount]);

  return (
    <Container className={css.container} spotlightId="search-result-type">
      {results &&
        results.map(({ title, category, data, count }, index) => (
          <SearchResultsType
            category={category}
            count={count}
            data={data}
            idx={index}
            key={category + "searchResult"}
            panelInfo={panelInfo}
            searchQueryRef={searchQueryRef}
            sectionTitle={title}
          />
        ))}
    </Container>
  );
});
