import React, { ReactNode, useEffect, useState } from 'react';
import { History, Location } from 'history';

export type RouteProps = {
  path: string;
  element: ReactNode;
};

type RouterProps = {
  history: History;
  children: React.ReactElement<RouteProps>[];
};

export const Route: React.FC<RouteProps> = ({ element }) => {
  return <>{element}</>;
};

export const Router: React.FC<RouterProps> = ({ history, children }) => {
  const [currentLocation, setCurrentLocation] = useState<Location>({
    pathname: '/',
    state: null,
    key: '',
    search: '',
    hash: '',
  });

  useEffect(() => {
    history.push('/');
    const handleRouteChange = ({ location }: { location: Location }) => {
      setCurrentLocation(location);
    };

    const unlisten = history.listen(handleRouteChange);

    return () => {
      unlisten();
    };
  }, [history]);

  const renderElement = () => {
    const routes = React.Children.toArray(
      children,
    ) as React.ReactElement<RouteProps>[];

    const route = routes.find((r) => r.props.path === currentLocation.pathname);

    if (route) {
      return route.props.element;
    }

    // Handle 404 page not found
    return <div>404 - Page Not Found</div>;
  };

  return <>{renderElement()}</>;
};

export default Router;
