import React from 'react';

interface DynamicOptions<TProps extends Record<string, unknown>> {
  ssr?: boolean;
  loading?: React.ComponentType<TProps>;
}

export function dynamic<TProps extends Record<string, unknown>>(
  factory: () => Promise<
    React.ComponentType<TProps> | { default: React.ComponentType<TProps> } | Record<string, unknown>
  >,
  { ssr = true, loading }: DynamicOptions<TProps> = {},
): React.ComponentType<TProps> {
  const Component = React.lazy(() =>
    factory().then((mod) => {
      // Case 1: factory() => import('./SomeModule') - direct import
      // Case 2: factory() => import('./SomeModule').then(mod => mod.default) - extract default
      if (typeof mod === 'function') {
        return { default: mod };
      }

      // Case 3: factory() => import('./SomeModule').then(mod => ({ default: mod.default })) - manual wrap
      // Case 4: factory() => import('./SomeModule').then(mod => ({ default: mod.Named })) - manual wrap named
      if (mod && typeof mod === 'object' && 'default' in mod) {
        const defaultExport = mod.default;

        // Handle both function components and React component objects (e.g., memo/forwardRef)
        if (typeof defaultExport === 'function') {
          return { default: defaultExport as React.ComponentType<TProps> };
        }

        if (defaultExport && typeof defaultExport === 'object' && '$$typeof' in defaultExport) {
          return { default: defaultExport as React.ComponentType<TProps> };
        }
      }

      // Case 5: factory() => import('./SomeModule').then(mod => mod.Named) - find named export
      if (mod && typeof mod === 'object') {
        const modObj = mod as Record<string, unknown>;

        for (const key in modObj) {
          const value = modObj[key];

          if (typeof value === 'function') {
            return { default: value as React.ComponentType<TProps> };
          }

          if (value && typeof value === 'object' && '$$typeof' in value) {
            return { default: value as React.ComponentType<TProps> };
          }
        }
      }

      throw new Error('Dynamic import did not return a valid React component');
    }),
  );

  const LoadingComponent: React.ComponentType<TProps> = loading || (() => null);

  return (props: TProps) => {
    const [hasMounted, setHasMounted] = React.useState(false);

    React.useEffect(() => {
      setHasMounted(true);
    }, []);

    if (ssr) {
      return (
        <React.Suspense fallback={<LoadingComponent {...props} />}>
          <Component {...props} />
        </React.Suspense>
      );
    }

    if (!hasMounted) {
      return <LoadingComponent {...props} />;
    }

    return (
      <React.Suspense fallback={<LoadingComponent {...props} />}>
        <Component {...props} />
      </React.Suspense>
    );
  };
}
