import React, { memo, useMemo } from 'react';
import ButtonGroup from '@mui/material/ButtonGroup';
import type { ButtonGroupProps } from '@mui/material/ButtonGroup';
import Button from '@mui/material/Button';
import type { MouseEventHandler } from 'react';
import clsx from 'clsx';

import createClasses from './styles';

export interface SegmentedTabsProps {
  /**
   * Items array that will be displayed as the segmented tabs.
   */
  items: {
    text: string;
    selected: boolean;
  }[];
  /**
   * The value is the text passed to the buttons.
   */
  clickHandler: (value: string) => MouseEventHandler<HTMLButtonElement>;
  /**
   * Prop which be passed into the ButtonGroup component.
   */
  buttonGroupProps?: ButtonGroupProps;
}

const SegmentedTabs = (props: SegmentedTabsProps) => {
  const { items, clickHandler, buttonGroupProps } = props;

  const classes = createClasses();

  const selectedIndex = useMemo(
    () => items.findIndex((item) => item.selected),
    [items]
  );

  return (
    <ButtonGroup {...buttonGroupProps}>
      {items.map((item, index) => {
        const { text } = item;
        return (
          <Button
            data-testid={text}
            key={text}
            onClick={clickHandler(text)}
            className={clsx(
              classes[selectedIndex === index ? 'selectedButton' : 'button'],
              selectedIndex !== -1 &&
                index === selectedIndex - 1 &&
                classes.beforeSelected,
              selectedIndex !== -1 &&
                index === selectedIndex + 1 &&
                classes.afterSelected
            )}
          >
            {text}
          </Button>
        );
      })}
    </ButtonGroup>
  );
};

SegmentedTabs.defaultProps = {
  buttonGroupProps: {
    size: 'small'
  }
};

const m = memo(SegmentedTabs);
export { m as SegmentedTabs };
