import * as React from 'react';
import {ChangeEvent, MouseEvent, SFC} from 'react';
import {Icon} from './../';
import {numberWithCommas} from './utils/number';

export interface DatagridPaginationProps {
  limitOptions: number[];
  limit: number;
  skip: number;
  total: number;
  onChangeLimit: (limit: number) => void;
  onChangeSkip: (skip: number) => void;
}

export const DatagridPagination: SFC<DatagridPaginationProps> = (props) => {
  const {limitOptions, limit, skip, total} = props;

  return (
    <div className="bkn-datagrid-pagination">
      {!total ? (
        <span className="text-uppercase hidden-xs-down">
          Results not found
        </span>
      ) : ([
        <span key={0} className="pagination-rows-select">Rows per page &nbsp;</span>,

        <div key={1} className="pagination-rows-select">
          <select
            className="form-control-sm custom-select"
            value={limit}
            onChange={handleChangeLimit(props)}
          >
            {limitOptions.map(o => (
              <option key={o} value={o}>{o}</option>
            ))}
          </select>
        </div>,

        <span key={2} style={{marginRight: '0.5rem'}}>
          {numberWithCommas(skip + 1)} - {numberWithCommas(pageLimit(limit, skip, total))}
          &nbsp;of&nbsp;
          <span>{numberWithCommas(total)}</span>
        </span>,

        <button
          key={3}
          className="btn btn-link btn-page-nav"
          type="button"
          style={{marginRight: '0.5rem'}}
          onClick={handleChangeSkip(props, 'prev')}
          disabled={(skip - limit) < 0}
        >
          <Icon name="chevron_left" />
        </button>,

        <button
          key={4}
          className="btn btn-link btn-page-nav"
          type="button"
          onClick={handleChangeSkip(props, 'next')}
          disabled={(skip + limit + 1) > total}
        >
          <Icon name="chevron_right" />
        </button>,
      ])}
    </div>
  );
};

DatagridPagination.displayName = 'DatagridPagination';

const handleChangeLimit = (props: DatagridPaginationProps) => (e: ChangeEvent<HTMLSelectElement>) => {
  props.onChangeLimit(parseInt(e.target.value, 10));
};

const handleChangeSkip = (props: DatagridPaginationProps, direction: 'prev' | 'next') => {
  return (e: MouseEvent<HTMLButtonElement>) => {
    const {limit, skip} = props;

    const updatedSkip = direction === 'next'
      ? skip + limit
      : skip - limit;

    props.onChangeSkip(updatedSkip);
  };
};

const pageLimit = (limit: number, skip: number, total: number) => {
  if ((skip + limit) > total) {
    return total;
  }

  return limit + skip;
};
