import { h } from '@stencil/core';
import { generatePagerItems } from '../../../utils/pagination';
import { arrayToClassString } from '../../../utils/ui';
import { DomNodeSubjectObserverFactory } from '../../../helpers/change-manager/subject/dom-node-subject/dom-node-subject-observer-factory';
import { VegaClick } from '../../../helpers/event-manager/event-id/vega-event-id';
export const VegaPaginationPageSelector = ({ total, current, onChange, pageCount, }) => {
  const pagerItem = (page) => {
    const isCurrent = current === page ? 'active' : '';
    const clickable = current !== page;
    return (
    /* no-noninteractive-element-to-interactive-role https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/main/docs/rules/no-noninteractive-element-to-interactive-role.md */
    h("li", { key: page, class: arrayToClassString(['vega-pagination-item', isCurrent]) },
      h("button", { 
        /* eslint-disable-next-line react/jsx-no-bind */
        onClick: () => clickable && onChange(page) }, page)));
  };
  /** Render the prev button of the pager **/
  const renderPrevButton = () => {
    const isDisabled = total === 0 || current === 1;
    return pagerButton('chevron-left', isDisabled, handlePrev);
  };
  /** Render the next button of the pager **/
  const renderNextButton = () => {
    const isDisabled = total === 0 || current === pageCount;
    return pagerButton('chevron-right', isDisabled, handleNext);
  };
  const renderPagers = () => {
    if (total === 0) {
      return [pagerItem(1)];
    }
    const pagerItems = generatePagerItems(current, pageCount);
    return pagerItems.map((item) => {
      if (typeof item === 'string') {
        return pagerEllipsis();
      }
      else {
        return pagerItem(item);
      }
    });
  };
  const pagerButton = (icon, isDisabled, handleClick) => {
    return (h("li", { class: arrayToClassString(['vega-pagination-button', isDisabled && 'disabled']) },
      h("vega-button-circle", { variant: "icon-only", icon: icon, iconColor: "text-link", size: "small", disabled: isDisabled, 
        /* eslint-disable-next-line react/jsx-no-bind */
        ref: (ref) => {
          DomNodeSubjectObserverFactory.addUniqueObserverToNode(ref, VegaClick, handleClick);
        } })));
  };
  const handlePrev = () => {
    onChange(current - 1);
  };
  const handleNext = () => {
    onChange(current + 1);
  };
  const pagerEllipsis = () => {
    return h("li", { class: "vega-pagination-item pager-ellipsis" }, "...");
  };
  return (h("ul", { class: "vega-pagination" },
    renderPrevButton(),
    renderPagers(),
    renderNextButton()));
};
