import { func, string, array, oneOfType, number } from 'prop-types';
import React from 'react';
import Icon from '../../Icon';
import { Shelf } from '../../Layout';
import { Text } from '../../Text';
import Tooltip from '../../Tooltip';

const TableSort = ({
  onSort,
  currentSort,
  justifyContent,
  sortProp,
  headerTitle,
  tooltip,
  className,
}) => {
  const sortProperties = Array.isArray(sortProp) ? sortProp : [sortProp];
  const isSelected = sortProperties.some((str) => currentSort.includes(str));
  const color = isSelected ? 'Orange' : 'Mid Neutral 3';
  const isDescending = sortProperties.some((str) => currentSort.includes(`-${str}`));

  return (
    <Shelf
      as="button"
      type="button"
      gap="xsmall"
      className={className}
      justifyContent={justifyContent}
      flexWrap="nowrap"
      onClick={() => onSort(sortProp)}
      data-testid={`sort-${sortProp}-btn`}
      width="100%"
    >
      <Text color={isSelected ? 'Dark Neutral 1' : 'Mid Neutral 1'}>{headerTitle}</Text>
      {tooltip && (
        <Tooltip content={tooltip} position="left">
          <Icon name="warning-circle" size={14} color="Mid Neutral 1" />
        </Tooltip>
      )}
      {<Icon name={isDescending ? 'arrow-up' : 'arrow-down'} size={9} color={color} />}
    </Shelf>
  );
};

TableSort.propTypes = {
  tooltip: string,
  className: string,
  justifyContent: string,
  headerTitle: string.isRequired,
  onSort: func.isRequired,
  sortProp: oneOfType([number, string, array]).isRequired,
  currentSort: string.isRequired,
};

export default TableSort;
