// @flow
import React, { useState, useCallback } from 'react';
import styled from 'styled-components';
import { getPaletteColor } from '../../../mixins/branding';
import { UnstyledButton } from '../unstyled-button';
import {
  getBgColor,
  getColor,
  getTabButtonFontSize,
  getAnimation,
  getBoxShadow,
} from './tab-set.css-rules';
import type { TabSetProps } from './tab-set.proptypes';
import { getSpacingRules } from '../../../mixins/spacing';

const TAB_BUTTON_MAX_WIDTH = 190;

export const TabButton = styled(UnstyledButton)`
  margin: 0px;
  position: relative;
  width: ${(props) => `${100 / props.totalTabs}`}%;
  border-radius: 25px;
  color: ${getColor};
  font-weight: 900;
  font-size: ${getTabButtonFontSize};
  text-align: center;
  z-index: 1;
`;

const Pill = styled.div`
  position: absolute;
  width: ${(props) => `${100 / props.totalTabs}`}%;
  height: 40px;
  border-radius: 25px;
  background-color: ${getBgColor};
  transform: translateX(${(props) => `${props.currentIndex * 100}%`});
  ${getAnimation}

  @media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
    left: ${(props) => `${(props.currentIndex * 100) / props.totalTabs}%`};
    transform: none;
  }
`;

export const TabList = styled.div`
  display: inline-flex;
  height: 40px;
  margin: 0;
  padding: 0;
  background-color: ${getPaletteColor('greyscale-light')};
  border-radius: 25px;
  box-shadow: ${getBoxShadow};
  position: relative;
  width: 100%;
  max-width: ${(props) => `${TAB_BUTTON_MAX_WIDTH * props.totalTabs}`}px;
`;

const useTabSetState = ({ selectedTabIndex, onSelect }) => {
  const [tabIndex, setTabIndex] = useState(selectedTabIndex);
  const [prevTabIndex, setPrevTabIndex] = useState(undefined);

  const handleTabSelect = useCallback(
    (index) => {
      setPrevTabIndex(tabIndex);
      setTabIndex(index);
    },
    [tabIndex],
  );

  const handleTabClick = useCallback(
    (index) => (_e) => {
      if (typeof onSelect === 'function') {
        onSelect(index);
      }
      handleTabSelect(index);
    },
    [handleTabSelect, onSelect],
  );

  return { tabIndex, prevTabIndex, handleTabClick };
};

const Container = styled.div`
  ${getSpacingRules};
`;

export const TabSet = ({
  selectedTabIndex = 0,
  tabs,
  onSelect,
  spacing,
  className,
  'data-qa': dataQa,
  'data-cy': dataCy,
  id,
  ...props
}: TabSetProps) => {
  const { tabIndex, prevTabIndex, handleTabClick } = useTabSetState({
    selectedTabIndex,
    onSelect,
  });

  return (
    <Container
      spacing={spacing}
      className={className}
      data-cy={dataCy}
      data-qa={dataQa}
      id={id}
      {...props}
    >
      <TabList role="tablist" totalTabs={tabs.length}>
        {tabs.map((tab, index) => (
          <React.Fragment key={tab.id}>
            <TabButton
              role="tab"
              key={tab.id}
              onClick={handleTabClick(index)}
              selected={tabIndex === index}
              totalTabs={tabs.length}
              insetFocus
            >
              {tab.label}
            </TabButton>
            {tabIndex === index && (
              <Pill
                selected={tabIndex === index}
                currentIndex={index}
                prevTabIndex={prevTabIndex}
                totalTabs={tabs.length}
              />
            )}
          </React.Fragment>
        ))}
      </TabList>
      <div role="tabpanel">{tabs[tabIndex].content}</div>
    </Container>
  );
};

TabSet.displayName = 'TabSet';
