import { Text, TouchableOpacity, Image, View } from 'react-native';
import type { ContentItem, ElementProperty } from '../types';
import { getElementContent, getElementImageUrl } from '../utils';
import { onClick } from '../utils/onClick';
import {
  getLayoutStyles,
  getTextStyles,
  getViewStyles,
} from '../utils/styleKeys';
import type { ContentViewItem } from '../store/contentModel';
import Resync from 'resync-javascript';
import { useEffect } from 'react';
import Icon from './icon';

/**
 * Basic element renderer without form dependencies
 * This is used to break the circular dependency between elements and forms
 */
export const RenderBasicElement = ({
  element,
  dataItem,
  contentItem,
}: {
  element: ContentItem;
  dataItem?: Record<string, any>;
  contentItem?: ContentViewItem;
}) => {
  useEffect(() => {
    if (element?.event && contentItem?.content?.id) {
      if (element.eventConfig?.action === 'view') {
        Resync.logEvent({
          eventId: element.event?.eventId,
          logId: element.eventConfig?.logId || '',
        });
        if (contentItem?.logAnalytics && element.eventConfig?.logId) {
          contentItem.logAnalytics(element.eventConfig?.logId, {
            itemId: element?.itemId,
            contentViewId: contentItem?.content?.id,
            ...element.eventConfig,
          });
        }
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (!element || !contentItem) return null;
  if (!element.isVisible) return null;

  const elementData = element.data as ElementProperty;
  const elementContent = getElementContent(element, dataItem || {});

  const handleClick = () => {
    if (element.eventConfig?.action === 'click' && contentItem?.content?.id) {
      Resync.logEvent({
        eventId: element.event?.eventId || '',
        logId: element.eventConfig?.logId || '',
      });
      if (contentItem?.logAnalytics && element.eventConfig?.logId) {
        contentItem.logAnalytics(element.eventConfig?.logId, {
          itemId: element?.itemId,
          contentViewId: contentItem?.content?.id,
          ...element.eventConfig,
          metadata: dataItem,
        });
      }
    }
    onClick({
      clickAction: elementData?.clickAction || null,
      functionRegistry: contentItem?.functionRegistry,
      navigationRegistry: contentItem?.navigationRegistry,
      dataItem: dataItem,
    });
  };

  switch (element.elementType) {
    case 'icon':
      return (
        <Icon
          {...(elementData.icon as {
            name: string;
            color: string;
            size: number;
            strokeWidth: number;
          })}
        />
      );
    case 'text':
      return (
        <Text
          style={[
            getTextStyles(elementData.styles),
            getTextStyles(elementData?.customStyles || {}),
            getViewStyles(elementData.styles),
            getViewStyles(elementData?.customStyles || {}),
          ]}
          {...elementData.customProps}
        >
          {elementContent}
        </Text>
      );

    case 'button':
      return (
        <TouchableOpacity
          key={element.itemId}
          style={[
            getLayoutStyles(elementData.styles),
            getLayoutStyles(elementData?.customStyles || {}),
            getViewStyles(elementData.styles),
            getViewStyles(elementData?.customStyles || {}),
            {
              ...(elementData?.properties?.iconPosition === 'left'
                ? {
                    display: 'flex',
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: 8,
                  }
                : {}),
              ...(elementData?.properties?.iconPosition === 'right'
                ? {
                    display: 'flex',
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: 8,
                  }
                : {}),
            },
          ]}
          onPress={handleClick}
          {...elementData.customProps}
        >
          {elementData?.icon?.name &&
            elementData.properties?.iconPosition === 'left' && (
              <Icon
                {...(elementData.icon as {
                  name: string;
                  color: string;
                  size: number;
                  strokeWidth: number;
                })}
              />
            )}
          <Text
            style={[
              getTextStyles(elementData.styles),
              getTextStyles(elementData?.customStyles || {}),
              {
                ...(!elementData?.properties?.iconPosition
                  ? { width: '100%', textAlign: 'center' }
                  : {}),
              },
            ]}
            {...elementData.customProps}
          >
            {elementContent}
          </Text>
          {elementData?.icon?.name &&
            elementData.properties?.iconPosition === 'right' && (
              <Icon
                {...(elementData.icon as {
                  name: string;
                  color: string;
                  size: number;
                  strokeWidth: number;
                })}
              />
            )}
        </TouchableOpacity>
      );

    case 'image':
      const imageUrl = getElementImageUrl(element, dataItem || {});

      if (elementData.clickAction) {
        return (
          <TouchableOpacity key={element.itemId} onPress={handleClick}>
            <Image
              source={{ uri: imageUrl }}
              style={[
                getLayoutStyles(elementData.styles),
                getLayoutStyles(elementData?.customStyles || {}),
                getViewStyles(elementData.styles),
                getViewStyles(elementData?.customStyles || {}),
              ]}
              {...elementData.customProps}
            />
          </TouchableOpacity>
        );
      }
      return (
        <Image
          source={{ uri: imageUrl }}
          style={[
            getLayoutStyles(elementData.styles),
            getLayoutStyles(elementData?.customStyles || {}),
            getViewStyles(elementData.styles),
            getViewStyles(elementData?.customStyles || {}),
          ]}
          {...elementData.customProps}
        />
      );

    case 'divider':
      return (
        <View
          style={{
            width: elementData.styles.width || elementData?.customStyles?.width,
            height:
              elementData.styles.height || elementData?.customStyles?.height,
            backgroundColor:
              elementData.styles.backgroundColor ||
              elementData?.customStyles?.backgroundColor,
          }}
        />
      );

    default:
      return null;
  }
};
