/*by Артур Франк https://vk.com/gmelum*/
import React, { FC, HTMLAttributes, Children, useState, useEffect, useRef, createContext, useMemo, startTransition } from "react";
import { getCN } from "../utils";
import "./TabsView.css";

interface ITabsView extends HTMLAttributes<HTMLDivElement> {
  activeTabs: string;
  delay?: number;
  safe?: boolean;
  nav?: string;
};

class SaveContext {
  private value: Record<string, number> = {};

  constructor(value: Record<string, number>) {
    this.value = value;
  };

  public getvalue = (title: string) => this.value[title] || 0;
  public setValue = (title: string, value: number) => this.value[title] = value;
};

export const ScrollContext = createContext<SaveContext>(new SaveContext({}));

const TabsView: FC<ITabsView> = ({
  activeTabs,
  delay = 400,
  safe = true, //Безопасная зона
  children,
  ...restProps
}) => {
  const scrollContext = useRef<SaveContext>(new SaveContext({})).current;

  const [[back, active, animation, show], setNav] = useState(["", activeTabs, false, true]);

  const views = useMemo(() => Children.toArray(children) as React.ReactElement[], [children]);
  const viewsNav = useMemo(() => views.map((i) => i.props.id), [children]);

  const pageBack = views.find((elem) => elem.props.id === back);
  const pageActive = views.find((elem) => elem.props.id === active);

  const indexBack = viewsNav.indexOf(back);
  const indexActive = viewsNav.indexOf(activeTabs);

  const isBack = indexActive < indexBack;
  const isNext = indexActive > indexBack;

  useEffect(() => {
    if (active !== activeTabs) {
      setNav([active, activeTabs, true, true]);

      const timer = window.setTimeout(() => {
        setNav([active, activeTabs, true, false]);
      }, delay);

      return () => window.clearTimeout(timer);
    };
  }, [activeTabs]);
  
  return (
    <div
      {...restProps}
      data-activeTabs={activeTabs}
      className={getCN([
        "TabsView",
        safe && "View__safe",
        isBack && animation && show && "TabsView__left",
        isNext && animation && show && "TabsView__right",
        (!animation || !show) && "TabsView__visible"
      ])}
    >
      <ScrollContext.Provider value={scrollContext}>
        {
          pageActive && (
            <div
              key={active}
              className={getCN("TabsView__active")}
            >
              {pageActive}
            </div>
          )
        }
        {
          animation && show && pageBack && (
            <div
              key={back}
              className={getCN("TabsView__back")}
            >
              {pageBack}
            </div>
          )
        }
      </ScrollContext.Provider>
    </div>
  );
};

export default TabsView;
