import React, { Suspense } from 'react';
import { useParams } from 'react-router-dom';
import { Loader, Center, Text, Stack, Alert } from '@mantine/core';
import { IconAlertCircle } from '@tabler/icons-react';
import Breadcrumbs from './Breadcrumbs';
import { microFrontends } from '../microfrontends.js';

// Pre-defined lazy imports for each microfrontend
// @ts-ignore - These modules are loaded at runtime via Module Federation
const DemoApp = React.lazy(() => import('demo/src/App'));
// @ts-ignore - These modules are loaded at runtime via Module Federation
const KMSApp = React.lazy(() => import('kms/src/App'));
// @ts-ignore - These modules are loaded at runtime via Module Federation
const FaaSApp = React.lazy(() => import('faas/src/App'));

// Map app names to components
const appComponents: Record<string, React.LazyExoticComponent<React.ComponentType<any>>> = {
  demo: DemoApp,
  kms: KMSApp,
  faas: FaaSApp,
};

const AppLoader: React.FC = () => {
  const { appName } = useParams<{ appName: string }>();

  const LoadingFallback = () => (
    <Center h={400}>
      <Stack align="center" gap="md">
        <Loader size="lg" />
        <Text>Loading {appName}...</Text>
      </Stack>
    </Center>
  );

  const ErrorFallback = ({ error }: { error: string }) => (
    <Alert
      icon={<IconAlertCircle size={16} />}
      title="Failed to load application"
      color="red"
      variant="light"
    >
      {error}
    </Alert>
  );

  const renderApp = () => {
    // Check if the app is registered in our microfrontends registry
    if (appName && appComponents[appName] && microFrontends[appName]) {
      const App = appComponents[appName];
      return (
        <Suspense fallback={<LoadingFallback />}>
          <App />
        </Suspense>
      );
    }
    
    return (
      <ErrorFallback 
        error={`Application "${appName}" is not available or not configured.`}
      />
    );
  };

  return (
    <Stack gap="md">
      <Breadcrumbs />
      {renderApp()}
    </Stack>
  );
};

export default AppLoader;
