import "./style.pcss";

import {
  useCallback,
  useEffect,
  useMemo,
  useState,
} from "react";
import type { FC, MouseEvent, ReactElement } from "react";
import { getWindow } from "ssr-window";
import type { INavigation, INavigationItem } from "./config/types";
import { NavigationContext } from "./context";
import { NavigationItem } from "./ui/NavigationItem";
import type { IComponentBaseProps } from "../../types/components";
import { useCN } from "../../utils/react/useCN";

/**
 * Компонент навигации
 * @returns {ReactElement}
 */
const Navigation: FC<INavigation & IComponentBaseProps> = ({
  baseClass = "navigation",
  form = null,
  children = null,
  items = [
    {
      isPrev: true,
      href: "#",
      icon: "icon-prev",
      isDisabled: true,
    },
    {
      isNext: true,
      href: "#",
      icon: "icon-next",
      isDisabled: false,
    },
  ],
  extraClasses = {},
  extraAttrs = {},
  separator = "",
  onClick = null,
  prevIconSrc = "icon-prev",
  nextIconSrc = "icon-next",
  prevIconSize = "medium",
  nextIconSize = "medium",
}): ReactElement => {
  const { getCN } = useCN(baseClass);
  const [ buttons, setButtons ] = useState(items);

  useEffect(() => {
    setButtons(items);
  }, [ items ]);

  const handleClick = useCallback((
    { event, data }:
    { event: MouseEvent; data: INavigationItem; }
  ) => {
    if (typeof onClick === "function") {
      onClick({
        event, data, pages: buttons, setPages: setButtons,
      });
    } else if (data.href) {
      event.preventDefault();
      getWindow().location.href = data.href;
    }
  }, [ buttons, onClick ]);

  const ctx = useMemo(() => ({
    getCN, items: buttons, form, separator, handleClick,
  }), [ buttons, form, separator, handleClick ]);

  return (
    <NavigationContext value={ctx}>
      <nav>
        <ul className={getCN("", extraClasses)} {...extraAttrs}>
          {!!buttons.length && buttons.map((btn) => {
            const computedBtn = {
              ...btn,
              ...(btn.isPrev ? { icon: prevIconSrc, iconSize: prevIconSize } : {}),
              ...(btn.isNext ? { icon: nextIconSrc, iconSize: nextIconSize } : {}),
            };

            const key = computedBtn.name || computedBtn.href || computedBtn.title || computedBtn.icon || `${computedBtn.isPrev ? "prev" : ""}_${computedBtn.isNext ? "next" : ""}`;
            return <NavigationItem isPrev={computedBtn.isPrev} isNext={computedBtn.isNext} key={key} {...computedBtn} />;
          })}
          {children}
        </ul>
      </nav>
    </NavigationContext>
  );
};

export type {
  INavigation,
  INavigationItem,
};

export { Navigation };
