import React from 'react';
import PropTypes from 'prop-types';
import { compose } from 'redux';
import { withRouter } from 'react-router-dom';
import componentRoutes from '../routes';

export function findRoute(routes, path) {
  let match;
  for (let i = 0; i < routes.length; i++) {
    const route = routes[i];
    if (route?.path === path) {
      match = route;
      break;
    }
    if (route?.routes) {
      match = findRoute(route.routes, path);
      if (match) {
        break;
      }
    }
  }
  return match;
}

function getParamsObject(params) {
  const paramsObject = {};
  params.forEach((value, key) => {
    if (paramsObject[key]) {
      // If the key already exists, convert the value to an array (to handle multiple values for the same key)
      paramsObject[key] = Array.isArray(paramsObject[key])
        ? [...paramsObject[key], value]
        : [paramsObject[key], value];
    } else {
      paramsObject[key] = value;
    }
  });
  return paramsObject;
}

function withReactRouterV3Compatibility(Component) {
  const EnhancedComponent = (props) => {
    const { history = {}, location = {}, match = {} } = props;
    const matchedRoute = findRoute(componentRoutes, match?.path);
    const newProps = {
      ...props,
      router: history,
      params: match?.params || [],
      route: matchedRoute,
      location: {
        ...location,
        query: getParamsObject(new URLSearchParams(location.search)),
      },
    };
    return <Component {...newProps} />;
  };
  EnhancedComponent.propTypes = {
    router: PropTypes.object,
    params: PropTypes.object,
    route: PropTypes.object,
  };
  return compose(
    withRouter,
  )(EnhancedComponent);
};

export default withReactRouterV3Compatibility;