import { getStrWithZeroFromNum } from "@web3r/flowerkit/str";
import type { FC, ReactElement } from "react";
import { useContext } from "react";
import type { IComponentBaseProps } from "../../../types/components";
import { Input } from "../../input";
import type { IPaginationItem } from "../config/types";
import { PaginationContext } from "../context";

/**
 * Компонент элемента пагинации.
 * @returns {ReactElement}
 */
export const PaginationItem: FC<IPaginationItem & IComponentBaseProps> = (props = {}): ReactElement => {
  const {
    getCN,
    form,
    separator,
    name,
    handleClick,
    handleChange,
  } = useContext(PaginationContext);

  const {
    children,
    onClick = handleClick,
    onChange = handleChange,
    isActive = false,
    isSeparator = false,
    page = 0,
    href = "",
    label = "",
    extraClasses = {},
    extraAttrs = {},
    title,
  } = props;

  let content = label;

  if (!content) {
    if (isSeparator) {
      content = separator ?? "";
    } else {
      content = getStrWithZeroFromNum(page);
    }
  }

  return (
    <li className={getCN("item", { isSeparator, isActive, ...extraClasses })} {...extraAttrs}>
      {children || (
        name ?
          <label title={title} className={getCN("link", { isInput: true })}>
            <Input
              id={name + page}
              extraClasses={{ isHidden: true }}
              isChecked={isActive}
              onChange={({ event, stateActions }) => onChange({ event, data: props, stateActions })}
              type={"radio"}
              name={name}
              value={page.toString()}
              form={form}
            />
            {content}
          </label> :
          <a
            title={title}
            onClick={(event) => onClick({ event, data: props })}
            href={href}
            className={getCN("link")}
          >
            {content}
          </a>
      )}
    </li>
  );
};
