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

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

import Spottable from "@enact/spotlight/Spottable";

import IcPartnersDefault from "../../../../../assets/images/ic-tab-partners-default@3x.png";
import { resetPanels, updatePanel } from "../../../../actions/panelActions";
import CustomImage from "../../../../components/CustomImage/CustomImage";
import useScrollReset from "../../../../hooks/useScrollReset";
import { panel_names } from "../../../../utils/Config";
import { $L } from "../../../../utils/helperMethods";
import css from "./QuickMenuItem.module.less";

const SpottableComponent = Spottable("li");

const STRING_CONF = {
  NEW: "NEW",
};

const QuickMenuItem = ({
  brandInfoItem,
  itemIndex,
  handleItemFocus,
  resetStates,
  scrollLeft,
  selectedPatnrId,
  label,
  ...rest
}) => {
  const { handleScrollReset, handleStopScrolling } = useScrollReset(
    scrollLeft,
    true
  );

  const dispatch = useDispatch();

  const panelInfo = useSelector((state) => state.panels.panels[0]?.panelInfo);

  const { logoImgAlt, logoImgPath, newFlag, patnrId, patncNm } = brandInfoItem;

  const handleBlur = useCallback(() => {
    if (itemIndex !== 0) {
      return;
    }

    handleStopScrolling();
  }, [handleStopScrolling, itemIndex]);

  const handleClick = useCallback(() => {
    if (patnrId === (selectedPatnrId ?? panelInfo?.patnrId)) {
      return;
    }

    const from = "menu";
    const name = panel_names.FEATURED_BRANDS_PANEL;

    dispatch(resetPanels([{ name }]));
    dispatch(updatePanel({ name, panelInfo: { from, patnrId } }));
    resetStates();
  }, [dispatch, patnrId, resetStates, selectedPatnrId]);

  const handleFocus = useCallback(() => {
    if (handleItemFocus) handleItemFocus();

    if (itemIndex !== 0) return;

    handleScrollReset();
  }, [handleScrollReset, handleItemFocus, itemIndex]);

  const newLabel = newFlag === "Y" ? "New " : "";
  const selected =
    (selectedPatnrId ?? panelInfo?.patnrId) === patnrId ? "Selected, " : "";
  const ariaLabel =
    newLabel + selected + "Channel " + patncNm + ", Tap " + label;

  return (
    <SpottableComponent
      className={classNames(
        css.brand,
        (selectedPatnrId ?? panelInfo?.patnrId) === patnrId && css.selected
      )}
      data-menu-index={itemIndex}
      onBlur={handleBlur}
      onClick={handleClick}
      onFocus={handleFocus}
      spotlightId={"spotlightId-" + patnrId}
      aria-label={ariaLabel}
      {...rest}
    >
      <div>
        <CustomImage
          src={logoImgPath}
          alt={logoImgAlt}
          fallbackSrc={IcPartnersDefault}
          ariaLabel={logoImgAlt}
        />
        {newFlag === "Y" && <div>{$L(STRING_CONF.NEW)}</div>}
      </div>
    </SpottableComponent>
  );
};

export default memo(QuickMenuItem);
