import cx from "classnames";
import React, { useMemo } from "react";
import { getItemState } from "./helpers";
import { PaginationItem } from "./PaginationItem";
import Separator from "./Separator";

interface PaginationItemProps {
  /** Page link href */
  href: string;
  /** Text label inside page item */
  label: string;
  /** Active state. */
  isActive?: boolean;
  /** aria-label of page item */
  ariaLabel?: string;
}

interface PaginationProps {
  /** Collapsed version */
  isCompact?: boolean;
  /** All pagination items - buttons & numbers */
  items: PaginationItemProps[];
  /** Accessibility label */
  label?: string;
  /** Additional CSS class name */
  className?: string;
  /** Additional props */
  [key: string]: any;
}

const CLASS_ROOT = "pagination";

export const Pagination: React.FC<PaginationProps> = ({
  className,
  label,
  isCompact,
  items,
  ...other
}) => {
  const classes = cx(CLASS_ROOT, className);

  const activeIndex = useMemo(
    () => items.findIndex(({ isActive }) => isActive),
    [items],
  );

  return (
    <nav aria-label={label}>
      <ul className={classes} {...other}>
        {items.map((item, index) => {
          const {
            isFirst,
            isHidden,
            isLast,
            isSecond,
            isSecondFromEnd,
            hasIcon,
            showSeparator,
          } = getItemState({
            activeIndex,
            items,
            isCompact: isCompact || false,
            index,
          });

          return (
            <React.Fragment key={index.toString()}>
              {!isCompact && showSeparator && isSecond && <Separator />}
              <PaginationItem
                {...item}
                ariaLabel={item.ariaLabel || item.label}
                isActive={item.isActive || false}
                isFirst={isFirst}
                isLast={isLast}
                className={cx({ hide: isHidden })}
                hasIcon={hasIcon}
              />
              {!isCompact && showSeparator && isSecondFromEnd && <Separator />}
            </React.Fragment>
          );
        })}
      </ul>
    </nav>
  );
};

Pagination.displayName = "Pagination";
