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

import classNames from "classnames";
import compose from "ramda/src/compose";
import { useDispatch, useSelector } from "react-redux";

import { Job } from "@enact/core/util";
import { Marquee, MarqueeController } from "@enact/sandstone/Marquee";
import Spotlight from "@enact/spotlight";
import Spottable from "@enact/spotlight/Spottable";

import css from "./TabItem.module.less";
import { sendLogTotalRecommend } from "../../actions/logActions";
import { LOG_CONTEXT_NAME, LOG_MESSAGE_ID } from "../../utils/Config";

const SpottableComponent = Spottable("div");
const TabItemBase = ({
  icons,
  title,
  expanded = false,
  mainSelected = false,
  selected = false,
  index = 0,
  target,
  deActivateTab,
  onClick,
  isSubItem,
  onFocus,
  showSubTab = false,
  opened,
  spotlightId,
  setLastFocusId,
  tabActivated,
  setSubTabLastFocusId,
  setSelectedTitle,
  length,
  ...rest
}) => {
  const [focused, setFocused] = useState(false);
  const dispatch = useDispatch();
  const { cursorVisible } = useSelector((state) => state.common.appStatus);
  const panels = useSelector((state) => state.panels.panels);
  const clearPressedJob = useRef(
    new Job((func) => {
      setTimeout(func, 0);
    }, 0)
  );

  useEffect(() => {
    if (mainSelected) {
      setLastFocusId(spotlightId);
      setSelectedTitle(title);
    }
    if (selected) {
      setLastFocusId(spotlightId);
      if (panels[0]?.panelInfo.spotlightId) {
        setSubTabLastFocusId(panels[0]?.panelInfo.spotlightId);
      }
    }
  }, [mainSelected, panels]);

  const _onClick = useCallback(
    (ev) => {
      clearPressedJob.current.start(() => {
        if (onClick) {
          if (target === undefined) {
            Spotlight.focus("activatedSub");
          }

          onClick({ index, target });

          if (spotlightId) {
            setLastFocusId(spotlightId);
          }
          if (target) {
            dispatch(
              sendLogTotalRecommend({
                contextName: LOG_CONTEXT_NAME.GNB,
                messageId: LOG_MESSAGE_ID.GNB,
                buttonTitle: title,
                buttonId: `GNB_CLICK_${title.toUpperCase().replace(" ", "_")}`,
              })
            );
          }
        }
      });
    },
    [target, index, onClick, showSubTab]
  );

  const _onFocus = useCallback(() => {
    setFocused(true);

    if (onFocus) {
      onFocus(index);
    }
  }, [index, showSubTab, onFocus]);

  const _onBlur = useCallback(() => {
    setFocused(false);
  }, [showSubTab]);

  const onKeyDown = useCallback(
    (event) => {
      if (event.key === "ArrowRight") {
        _onClick();
        //  onClick({ index, target });
      }
    },
    [deActivateTab, onClick, index, target]
  );

  const renderIcon = useCallback(() => {
    if (!icons) {
      return null;
    }

    const Component = icons;
    let iconType = "normal";

    if (expanded && opened) {
      iconType = "focused";
    } else if (selected) {
      iconType = "selected";
    } else if (mainSelected) {
      iconType = "selected";
    } else if (focused) {
      iconType = "focused";
    } else if (expanded) {
      iconType = "expanded";
    }

    return <Component iconType={iconType} />;
  }, [
    focused,
    expanded,
    mainSelected,
    opened,
    index,
    icons,
    selected,
    cursorVisible,
  ]);

  const TextComponent = useCallback(() => {
    return (
      <>
        {title && (
          <Marquee
            marqueeDisabled={!focused}
            className={classNames(css.text, isSubItem && css.subItem)}
            marqueeOn={"focus"}
          >
            {title}
          </Marquee>
        )}
      </>
    );
  }, [title, focused, expanded]);

  delete rest.hasChildren;
  delete rest.getChildren;
  return (
    <SpottableComponent
      className={classNames(
        css.tabItem,
        expanded && focused && css.focused,
        expanded && opened && css.opened,
        !isSubItem && opened && showSubTab && css.arrow,
        !focused && expanded && mainSelected && css.selected,
        !focused && expanded && selected && css.selected
      )}
      onKeyDown={onKeyDown}
      onFocus={_onFocus}
      onBlur={_onBlur}
      onClick={_onClick}
      spotlightId={spotlightId}
      role="button"
    >
      <div
        className={classNames(
          css.itemWrap,
          expanded && opened && css.opened,
          expanded && mainSelected && css.selected,
          expanded && selected && css.selected
        )}
      >
        {icons && <div className={css.icon}>{renderIcon()}</div>}
        <TextComponent />
      </div>
    </SpottableComponent>
  );
};
const ItemDecorator = compose(MarqueeController({ marqueeOnFocus: true }));
const TabItem = ItemDecorator(TabItemBase);

export default TabItem;
