import React, {useState, useEffect, useMemo } from 'react';
import {YRouteProps} from './router.interface';
import {useHistory} from './useHistory';
import {RouteStyled} from './styles';

export const YRoute: React.FC<YRouteProps> = ({ children, path, isCurrent, parentPath, grandPath, title, isStatic, ...rest }) => {
  const {state, registerRoute} = useHistory();
  const {current, history, routes} = state;
  const [disable, setDisable] = useState(!isCurrent);
  const [hasShowed, setHasShowed] = useState(isCurrent);

  const matchCurrentRoute = () => {
    setDisable(!isCurrent);
    let route = routes[path];
    let newPath = path;
    if(grandPath && parentPath && routes[grandPath] && routes[grandPath]['children'] && routes[grandPath]['children'][parentPath] && routes[grandPath]['children'][parentPath]['children']) {
      route = routes[grandPath]['children'][parentPath]['children'][path];
    } else if (parentPath && !grandPath) {
      route = routes[parentPath]['children'][path];
    }
    if(route && route.isDefault && parentPath) {
      newPath = parentPath;
    }
    const hasHistory = history.length ? history.includes(newPath) : isCurrent;
    setHasShowed(isStatic ? isCurrent || hasHistory : isCurrent);
  }

  useMemo(() => {
    registerRoute({
      ...rest,
      parentPath,
      grandPath,
      path,
      title,
    })
  }, []);

  useEffect(() => {
    if(current.path) {
      matchCurrentRoute();
    }
  }, [isCurrent]);


  return (
    <RouteStyled
      data-title={title}
      disable={disable}
      data-path={path}
      data-parent={parentPath}
      data-disable={disable}
    >
      {hasShowed ? children: null}
    </RouteStyled>
  );
};
