import { lazy, Suspense } from 'react';
import React from 'react';

/**
 * Loading spinner component
 */
const LoadingSpinner: React.FC<{ message?: string }> = ({ message = 'Loading...' }) => (
  <div className="flex flex-col items-center justify-center p-8">
    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-kaspersky-base mb-3"></div>
    <p className="text-kaspersky-text text-sm">{message}</p>
  </div>
);

/**
 * Lazy loading of heavy components
 */
export const LazyGuacamoleViewer = lazy(() =>
  import('./GuacamoleViewer').then((module) => ({ default: module.default }))
);

export const LazyMachineCredentialsModal = lazy(() =>
  import('./MachineCredentialsModal').then((module) => ({ default: module.default }))
);

/**
 * HOC for wrapping components in Suspense
 */
export const withSuspense = <P extends object>(
  Component: React.ComponentType<P>,
  loadingMessage?: string
) => {
  const WrappedComponent: React.FC<P> = (props) => (
    <Suspense fallback={<LoadingSpinner message={loadingMessage} />}>
      <Component {...props} />
    </Suspense>
  );

  WrappedComponent.displayName = `withSuspense(${Component.displayName || Component.name})`;
  return WrappedComponent;
};

/**
 * Ready-to-use components with Suspense
 */
export const GuacamoleViewerWithSuspense = withSuspense(
  LazyGuacamoleViewer,
  'Loading remote connection...'
);

export const MachineCredentialsModalWithSuspense = withSuspense(
  LazyMachineCredentialsModal,
  'Loading connection form...'
); 