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';

const DemoApp = React.lazy(() => import('demo/App'));
const KMSApp = React.lazy(() => import('kms/App'));

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 = () => {
    switch (appName) {
      case 'demo':
        return (
          <Suspense fallback={<LoadingFallback />}>
            <DemoApp />
          </Suspense>
        );
      case 'kms':
        return (
          <Suspense fallback={<LoadingFallback />}>
            <KMSApp />
          </Suspense>
        );
      default:
        return (
          <ErrorFallback 
            error={`Application "${appName}" is not available or not configured.`}
          />
        );
    }
  };

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

export default AppLoader;