import { useEffect, useState } from 'react';
import type { ReactNode } from 'react';
import type {
  NavigationRegistry,
  FunctionRegistry,
  LogAnalytics,
} from './types';
import Resync from 'resync-javascript';
import { useResync } from './hooks/useResync';
import ResyncContentBlock from './ResyncContentBlock';

/**
 * Resync Content View Component
 * Renders dynamic content blocks in React Native apps
 */

interface ResyncCampaignViewProps {
  name: string;
  loadingComponent?: React.ReactNode;
  errorComponent?: React.ReactNode;
  emptyComponent?: React.ReactNode;
  // Enhanced props for dynamic function handling
  functionRegistry?: FunctionRegistry;
  navigationRegistry?: NavigationRegistry;
  logAnalytics?: LogAnalytics;
}

export const ResyncCampaignView = ({
  name,
  loadingComponent,
  errorComponent,
  emptyComponent,
  functionRegistry,
  navigationRegistry,
  logAnalytics,
}: ResyncCampaignViewProps): ReactNode => {
  const { loaded, isLoading, loadFailed } = useResync();

  const [contentView, setContentView] = useState<string | null>(null);

  useEffect(() => {
    if (!loaded || loadFailed || isLoading) {
      return;
    }
    const loadVariant = async () => {
      const variant = await Resync.getVariant(name);
      console.log('loaded new variant ==================', variant);
      const allContent = await Resync.getContent();
      const foundContent = (allContent || [])?.find(
        (item: any) => item.id === variant
      );
      if (foundContent) {
        setContentView(foundContent.name);
      }
    };
    if (name) {
      loadVariant();
    }
  }, [name, loaded, isLoading, loadFailed, contentView]);

  return contentView ? (
    <ResyncContentBlock
      name={contentView}
      functionRegistry={functionRegistry}
      navigationRegistry={navigationRegistry}
      logAnalytics={logAnalytics}
      loadingComponent={loadingComponent}
      errorComponent={errorComponent}
      emptyComponent={emptyComponent}
    />
  ) : null;
};

export default ResyncCampaignView;
