import React, { useMemo, useState } from 'react';
import {
  Route,
  RouteProps,
  Router,
  Routes as ReactRouters,
  useNavigate,
} from 'react-router-dom';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { WixPatternsRouterContext } from '../../providers/WixPatternsRouterProvider';
import { PatternsReactRoute } from './PatternsReactRoute';
import { createPlatformizedNavigator } from './createPlatformizedNavigator';
import { WixPatternsRouterState } from '../../state/WixPatternsRouterState';

const convertToRoute = (child: React.ReactNode) => {
  if (React.isValidElement(child) && child.type === PatternsReactRoute) {
    const routeProps = child.props as RouteProps;
    return <Route {...routeProps} />;
  }
  return child;
};

const Routers = ({ children }: { children: React.ReactNode }) => {
  const navigate = useNavigate();

  const container = useWixPatternsContainer();

  const [routerState] = useState(
    () => new WixPatternsRouterState({ container, navigate }),
  );

  return (
    <WixPatternsRouterContext.Provider value={routerState}>
      <ReactRouters>
        {React.Children.map(children, convertToRoute)}
      </ReactRouters>
    </WixPatternsRouterContext.Provider>
  );
};

export const PatternsReactRouter = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const container = useWixPatternsContainer();
  const pageLocation = container.usePageLocation?.();

  if (!pageLocation) {
    throw new Error(
      'It appears that `PatternsReactRouter` is being used incorrectly. Please refer to the documentation to ensure proper implementation.',
    );
  }

  const navigator = useMemo(
    () => createPlatformizedNavigator({ pageLocation, container }),
    [pageLocation],
  );

  return (
    <Router navigator={navigator} location={pageLocation}>
      <Routers>{children}</Routers>
    </Router>
  );
};
