// src/components/ScreenBuilder/index.tsx
import { ThemedText } from '@components/ThemedText';
import Tile from '@components/Tile';
import React from 'react';
import {
  View,
  ScrollView,
  StyleSheet
} from 'react-native';
import { styles } from './styles';

// Define the configuration types
export interface ComponentConfig {
  type: string;
  props?: Record<string, any>;
  style?: Record<string, any>;
}

export interface ScreenConfig {
  components: ComponentConfig[];
  scrollable?: boolean;
  style?: Record<string, any>;
}

interface ScreenBuilderProps {
  config: ScreenConfig;
  screenWidth: number;
}

const ScreenBuilder: React.FC<ScreenBuilderProps> = ({ config, screenWidth }) => {
  // Component registry - maps component types to actual components
  const componentRegistry: Record<string, React.ComponentType<any>> = {
    // Tile wrapper components
    'AccountCard': (props: any) => <Tile type="account" data={props} />,
    'CreditCard': (props: any) => <Tile type="creditCard" data={props} />,
    'ServiceCard': (props: any) => <Tile type="service" data={props} />,
    'ServiceGrid': (props: any) => <Tile type="serviceGrid" data={props} />,
    'PromotionalCard': (props: any) => <Tile type="promotional" data={props} />,

    // Simple components
    'SectionHeader': ({ title }: { title: string }) => (
      <ThemedText variant="subheading" style={styles.sectionHeader}>
        {title}
      </ThemedText>
    ),

    // Placeholder for animated horse - we'll create this next
    'AnimatedHorse': () => (
      <View style={styles.animatedContainer}>
        <ThemedText variant="body" style={styles.placeholder}>
          🐎 Animated Horse Coming Soon
        </ThemedText>
      </View>
    ),
  };

  const renderComponent = (componentConfig: ComponentConfig, index: number) => {
    const { type, props = {}, style = {} } = componentConfig;

    const Component = componentRegistry[type];

    if (!Component) {
      console.warn(`Component type "${type}" not found in registry`);
      return null;
    }

    return (
      <View key={index} style={style}>
        <Component {...props} />
      </View>
    );
  };

  const content = (
    <View style={[styles.container, { width: screenWidth }, config.style]}>
      <View style={styles.contentPadding}>
        {config.components.map((componentConfig, index) =>
          renderComponent(componentConfig, index)
        )}
      </View>
    </View>
  );

  // Return scrollable or non-scrollable version based on config
  if (config.scrollable !== false) {
    return (
      <ScrollView
        style={styles.scrollContainer}
        showsVerticalScrollIndicator={false}
        contentContainerStyle={styles.scrollContent}
      >
        {content}
      </ScrollView>
    );
  }

  return content;
};

export default ScreenBuilder;