import { useLocation } from 'react-router-dom';
import { usePluginStore } from '@/store/pluginStore';
import { PluginPage } from './PluginLoader';

/**
 * PluginRouteRenderer — catch-all route handler that checks the current URL
 * against all plugin page_routes from the plugin store.
 *
 * If a matching route is found, it renders the plugin's page component.
 * Otherwise it renders a simple "Not Found" message.
 *
 * This component is intended to be used as the last child of the protected
 * route group in routes/index.tsx:
 *   { path: '*', element: <PluginRouteRenderer /> }
 */
export function PluginRouteRenderer() {
  const location = useLocation();
  const getAllPageRoutes = usePluginStore((s) => s.getAllPageRoutes);
  const loaded = usePluginStore((s) => s.loaded);

  const routes = getAllPageRoutes();

  // Find the first matching route (exact match or prefix match for nested routes)
  const matchedRoute = routes.find((r) => {
    // Exact match
    if (location.pathname === r.path) return true;
    // Prefix match for nested routes (e.g. /calendar/settings matches /calendar)
    if (r.path !== '/' && location.pathname.startsWith(r.path + '/')) return true;
    return false;
  });

  if (matchedRoute) {
    // Find the plugin name for display
    const manifests = usePluginStore.getState().manifests;
    const plugin = manifests.find((m) =>
      m.page_routes.some((pr) => pr.path === matchedRoute.path)
    );
    const pluginName = plugin?.display_name || plugin?.name || matchedRoute.path;

    return (
      <PluginPage
        component={matchedRoute.component}
        pluginName={pluginName}
      />
    );
  }

  // If manifests haven't loaded yet, show nothing (the static router handles it)
  if (!loaded) {
    return null;
  }

  // No plugin route matched — show a simple not-found
  return (
    <div className="flex flex-col items-center justify-center min-h-[50vh] text-secondary-500">
      <h2 className="text-2xl font-semibold mb-2">Page Not Found</h2>
      <p className="text-sm">
        The page <code className="bg-secondary-100 px-1 rounded">{location.pathname}</code> was not found.
      </p>
    </div>
  );
}
