import React, { useCallback } from "react";

import classNames from "classnames";

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

import useScrollReset from "../../hooks/useScrollReset";
import { $L } from "../../utils/helperMethods";
import css from "./TButtonTab.module.less";
import TButtonTabItem from "./TButtonTabItem";

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

export const LIST_TYPE = {
  large: "large",
  medium: "medium",
  small: "small",
};

export const COLOR_TYPE = {
  gray: "gray",
  white: "white",
};

export const RIGHT_BUTTON_TYPE = {
  sort: "sort",
};

export default function TButtonTab({
  className,
  selectedIndex,
  onItemClick,
  contents = [],
  noMarquee = false,
  listType = LIST_TYPE.medium,
  colorType = COLOR_TYPE.white,
  spotlightId,
  onSpotlightLeft,
  spotlightDisabled,
  scrollTop,
  ...rest
}) {
  const { handleScrollReset, handleStopScrolling } = useScrollReset(scrollTop);

  const onClick = useCallback(
    (index) => (e) => {
      if (onItemClick) {
        if (selectedIndex === index && scrollTop) {
          return scrollTop();
        }

        onItemClick({ index, e });

        if (scrollTop) {
          scrollTop();
        }
      }
    },
    [selectedIndex, scrollTop]
  );

  return (
    <Container
      className={classNames(css.tabs, css[listType], css[colorType], className)}
      spotlightId={spotlightId}
      {...rest}
    >
      {contents.map((item, index) => {
        const selectedText = "Selected, ";
        let ariaLabelText = null;
        const selectedChk = index === selectedIndex;
        if (selectedChk) {
          ariaLabelText =
            selectedText +
            item +
            ", tab, " +
            (index * 1 + 1) +
            " of " +
            contents.length;
        } else {
          ariaLabelText =
            item + ", tab, " + (index * 1 + 1) + " of " + contents.length;
        }
        return (
          <TButtonTabItem
            key={`buttonTabItem ${index}`}
            selected={index === selectedIndex}
            onClick={onClick(index)}
            index={index}
            spotlightId={`tab-${index}`}
            selectedTabIndex={selectedIndex}
            noMarquee={noMarquee}
            listType={listType}
            colorType={colorType}
            onSpotlightLeft={onSpotlightLeft}
            onFocus={handleScrollReset}
            onBlur={handleStopScrolling}
            ariaLabel={ariaLabelText}
            spotlightDisabled={spotlightDisabled}
          >
            {item}
          </TButtonTabItem>
        );
      })}
    </Container>
  );
}
