import React, { ReactElement } from 'react';
import css from '../../utils/css';

import { PaginationWrapper, PageNumber } from './StyledPagination';
import Icon from '../Icon';
import assert from '../../utils/assert';

import { CommonProps } from '../common';
import { generatePages, getDisplayState, SPREADING_SYMBOL } from './utils';

export interface PaginationProps extends CommonProps {
  /**
   * Current selected page. This is 1-based indexing.
   */
  current: number;
  /**
   * Change event handler receiving new selected page.
   */
  onChange: (selectedPage: number) => void;
  /**
   * Total number of pages.
   */
  total: number;
}

const Pagination = ({
  current,
  total,
  onChange,
  id,
  className,
  style,
  sx = {},
  'data-test-id': dataTestId,
}: PaginationProps): ReactElement => {
  assert(
    current !== 0,
    `[Pagination] 0 for 'current' prop is invalid, you may use 1 instead.`
  );

  const pages = generatePages({ current, total });

  return (
    <PaginationWrapper
      id={id}
      className={className}
      style={{ ...style, ...css(sx) }}
      data-test-id={dataTestId}
    >
      <PageNumber
        type="button"
        themeDisplayAs={current === 1 ? 'disabled' : 'navigator'}
        onClick={(): void => onChange(current - 1)}
      >
        <Icon icon="arrow-left" size="small" />
      </PageNumber>
      {pages.map((pageNumber, index) => {
        const displayAs = getDisplayState({ current, pageNumber });
        return (
          <PageNumber
            key={
              pageNumber !== SPREADING_SYMBOL
                ? pageNumber
                : `${pageNumber}-${index}`
            }
            type="button"
            themeDisplayAs={displayAs}
            onClick={
              pageNumber === SPREADING_SYMBOL
                ? undefined
                : (): void => onChange(pageNumber)
            }
          >
            {pageNumber !== SPREADING_SYMBOL ? (
              pageNumber
            ) : (
              <Icon icon="more-horizontal" size="xsmall" intent="text" />
            )}
          </PageNumber>
        );
      })}
      <PageNumber
        type="button"
        themeDisplayAs={current === total ? 'disabled' : 'navigator'}
        onClick={(): void => onChange(current + 1)}
      >
        <Icon icon="arrow-right" size="small" />
      </PageNumber>
    </PaginationWrapper>
  );
};

export default Pagination;
