import { useContext } from "react";
import type { FC, MouseEvent, ReactElement } from "react";
import type { IComponentBaseProps } from "../../../types/components";
import { Icon } from "../../icon";
import type { INavigationItem } from "../config/types";
import { NavigationContext } from "../context";

/**
 * Компонент элемента навигации.
 * @returns {ReactElement} Элемент навигации.
 */
export const NavigationItem: FC<INavigationItem & IComponentBaseProps> = (props = {}): ReactElement => {

  const { getCN, handleClick } = useContext(NavigationContext);

  const {
    children,
    name,
    onClick = handleClick,
    href = "",
    extraClasses = {},
    extraAttrs = {},
    title,
    icon = "icon-next",
    iconSize = "medium",
    isPrev,
    isNext,
    isDisabled = false,
  } = props;

  const classes = {
    isDisabled, isPrev, isNext, ...extraClasses,
  };

  const onLinkClick = isDisabled
    ? undefined
    : (event: MouseEvent) => onClick({ event, data: props });

  let content = children;

  if (!content) {
    if (isDisabled) {
      content = <div className={getCN("link")}><Icon src={icon} size={iconSize} /></div>;
    } else if (name) {
      content = (
        <label htmlFor={name} title={title} className={getCN("link", { isInput: true })}>
          <Icon src={icon} size={iconSize} />
        </label>
      );
    } else {
      content = (
        <a rel={isPrev ? "prev" : "next"} title={title} onClick={onLinkClick} href={href} className={getCN("link")}>
          <Icon src={icon} size={iconSize} />
        </a>
      );
    }
  }

  return (
    <li className={getCN("item", classes)} {...extraAttrs}>
      {content}
    </li>
  );
};
