/* eslint-disable react-native/no-inline-styles */
import { ImageBackground, Pressable, ScrollView, View } from 'react-native';
import { useEffect } from 'react';
import type { ReactNode } from 'react';
import type { ContentItem, SectionProperty } from '../types';
import { RenderElement } from './element';
import { onClick } from '../utils/onClick';
import { Fragment } from 'react/jsx-runtime';
import { getLayoutStyles, getViewStyles } from '../utils/styleKeys';
import { type ContentViewItem } from '../store/contentModel';
import { getChildren } from '../utils';
import Resync from 'resync-javascript';
import { FormRenderer } from '../FormElements';

export const RenderSection = ({
  section,
  contentItem,
  dataItem,
  formValues,
  formHandlers,
  formState,
}: {
  section?: ContentItem;
  contentItem?: ContentViewItem;
  dataItem?: Record<string, any>;
  formValues?: Record<string, any>;
  formHandlers?: {
    handleChange: (field: string) => (value: any) => void;
    handleBlur: (field: string) => () => void;
    handleSubmit: () => void;
    setFieldTouched: (field: string) => void;
  };
  formState?: {
    errors: Record<string, any>;
    touched: Record<string, any>;
    isSubmitting: boolean;
  };
}): ReactNode => {
  useEffect(() => {
    if (section?.event && contentItem?.content?.id) {
      if (section.eventConfig?.action === 'view') {
        Resync.logEvent({
          eventId: section.event?.eventId || '',
          logId: section.eventConfig?.logId || '',
        });
        if (contentItem?.logAnalytics && section.eventConfig?.logId) {
          contentItem.logAnalytics(section.eventConfig?.logId, {
            itemId: section?.itemId,
            contentViewId: contentItem?.content?.id,
            ...section.eventConfig,
          });
        }
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (!section || !contentItem) return null;

  const sectionData = section?.data as SectionProperty;

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

  // Get child elements of this section that are visible
  const children = getChildren(section?.itemId, contentItem?.content);

  // Check if section is scrollable
  const isScrollable = section.isScrollable;
  const scrollOptions = sectionData.scrollOptions || { scrollType: 'vertical' };

  // Render children
  const renderChildren = () => (
    <>
      {children.map((child) => (
        <Fragment key={child.itemId}>
          {child.type === 'section' ? (
            <RenderSection
              section={child}
              contentItem={contentItem}
              dataItem={dataItem || {}}
            />
          ) : [
              'input',
              'select',
              'checkbox',
              'submit',
              'radio',
              'textarea',
            ].includes(child.elementType as string) ? (
            // Render form element with form state
            <FormRenderer
              key={child.itemId}
              element={child as any}
              value={formValues?.[child.name]}
              onChange={formHandlers?.handleChange(child.name) || (() => {})}
              onBlur={() =>
                formHandlers?.setFieldTouched(child.name) || (() => {})
              }
              onSubmit={formHandlers?.handleSubmit || (() => {})}
              error={formState?.errors[child.name] as string}
              touched={formState?.touched[child.name] as boolean | undefined}
              disabled={formState?.isSubmitting}
              loading={formState?.isSubmitting}
              contentItem={contentItem}
            />
          ) : (
            <RenderElement
              element={child}
              contentItem={contentItem}
              dataItem={dataItem || {}}
            />
          )}
        </Fragment>
      ))}
    </>
  );

  if (sectionData.backgroundImage) {
    return (
      <ImageBackground
        source={{ uri: sectionData.backgroundImage }}
        style={{
          borderRadius:
            sectionData.styles?.borderRadius ||
            sectionData?.customStyles?.borderRadius ||
            0,
          overflow: 'hidden',
          zIndex: 10,
          ...(sectionData.styles?.flex || sectionData?.customStyles?.flex
            ? {
                display: 'flex',
                flex:
                  sectionData.styles?.flex || sectionData.customStyles?.flex,
              }
            : {}),
          ...(sectionData.styles?.height || sectionData.customStyles?.height
            ? {
                height:
                  sectionData.styles?.height ||
                  sectionData?.customStyles?.height,
              }
            : {}),
          // flex: 1,
        }}
        resizeMode={sectionData?.customStyles?.resizeMode || 'cover'}
      >
        <View
          style={[
            getLayoutStyles(sectionData.styles),
            getLayoutStyles(sectionData?.customStyles || {}),
            getViewStyles(sectionData.styles),
            getViewStyles(sectionData?.customStyles || {}),
            {
              backgroundColor: 'transparent', // Ensure background is transparent when using ImageBackground
              // flex: 1,
            },
          ]}
          {...section.data.customProps}
        >
          {renderChildren()}
        </View>
      </ImageBackground>
    );
  }

  // If scrollable, wrap in ScrollView
  if (isScrollable) {
    return (
      <ScrollView
        horizontal={scrollOptions.scrollType === 'horizontal'}
        showsHorizontalScrollIndicator={false}
        showsVerticalScrollIndicator={false}
        contentContainerStyle={[
          getLayoutStyles(sectionData.styles),
          getLayoutStyles(sectionData?.customStyles || {}),
          getViewStyles(sectionData.styles),
          getViewStyles(sectionData?.customStyles || {}),
        ]}
        {...section.data.customProps}
      >
        {renderChildren()}
      </ScrollView>
    );
  }

  if (sectionData.clickAction) {
    return (
      <Pressable
        onPress={() => handleClick()}
        key={section.itemId}
        style={[
          getLayoutStyles(sectionData.styles),
          getLayoutStyles(sectionData?.customStyles || {}),
          getViewStyles(sectionData.styles),
          getViewStyles(sectionData?.customStyles || {}),
        ]}
      >
        {renderChildren()}
      </Pressable>
    );
  }

  // Non-scrollable section
  return (
    <View
      key={section.itemId}
      style={[
        getLayoutStyles(sectionData.styles),
        getLayoutStyles(sectionData?.customStyles || {}),
        getViewStyles(sectionData.styles),
        getViewStyles(sectionData?.customStyles || {}),
      ]}
      {...section.data.customProps}
    >
      {renderChildren()}
    </View>
  );
};
