import clsx from "clsx";
import { UsePaginationItem } from "libs/hooks/usePagination";
import { ElementType, forwardRef, ReactNode } from "react";

import styles from "./index.module.scss";

export interface PaginationItemProps extends Docs {
  className?: string;
  component?: ElementType;
  /**
   * The components used for first, last, next & previous item type
   * @default {
   *   first: FirstPageIcon,
   *   last: LastPageIcon,
   *   next: NavigateNextIcon,
   *   previous: NavigateBeforeIcon,
   * }
   */
  components?: {
    first?: string;
    last?: string;
    next?: string;
    previous?: string;
  };
  /**
   * If `true`, the component is disabled.
   * @default false
   */
  disabled?: boolean;
  /**
   * The current page number.
   */
  page?: ReactNode;
  /**
   * If `true` the pagination item is selected.
   * @default false
   */
  selected?: boolean;
  /**
   * The type of pagination item.
   * @default 'page'
   */
  type?: UsePaginationItem["type"];
}

const PaginationItem = forwardRef<HTMLDivElement, PaginationItemProps>(
  function PaginationItem(props, ref) {
    const {
      className,
      component: PaginationItemPage = "button",
      components = {
        previous: "navigate-prev",
        next: "navigate-next",
        first: "first-page",
        last: "last-page",
      },
      disabled = false,
      page,
      selected = false,
      type = "page",
      ...other
    } = props;

    const normalizedIcons = {
      previous: components.previous || "navigate-prev",
      next: components.next || "navigate-next",
      first: components.first || "first-page",
      last: components.last || "last-page",
    };

    const icon = normalizedIcons[type as keyof typeof normalizedIcons];

    return type === "start-ellipsis" || type === "end-ellipsis" ? (
      <div ref={ref} className={clsx(styles.text, className)}>
        …
      </div>
    ) : (
      <PaginationItemPage
        ref={ref}
        disabled={disabled}
        className={clsx(styles.item, className, {
          [styles.selected]: selected,
          [styles.disabled]: disabled,
        })}
        {...other}
      >
        {type === "page" && page}
        {icon ? (
          <svg className={styles.icon}>
            <use xlinkHref={`/icons.svg#${icon}`}></use>
          </svg>
        ) : null}
      </PaginationItemPage>
    );
  }
);

export default PaginationItem;
