/* eslint-disable react-native/no-inline-styles */
import { View, Pressable, FlatList, StyleSheet, Text } from 'react-native';
import { useEffect } from 'react';
import type { ReactNode } from 'react';
import type { ContentItem, ListProperty } from '../types';
import { RenderSection } from './section';
import { onClick } from '../utils/onClick';
import { getLayoutStyles, getViewStyles } from '../utils/styleKeys';
import { Fragment } from 'react/jsx-runtime';
import { type ContentViewItem } from '../store/contentModel';
import { getChildren } from '../utils';
import Resync from 'resync-javascript';

// const renderListItemSeparator = ({
//   isHorizontal,
//   gap,
// }: {
//   isHorizontal: boolean;
//   gap: number;
// }) => (
//   <View style={isHorizontal ? { width: gap || 0 } : { height: gap || 0 }} />
// );

export const RenderList = ({
  list,
  contentItem,
}: {
  list: ContentItem;
  contentItem?: ContentViewItem;
}): ReactNode => {
  useEffect(() => {
    if (list?.event && contentItem?.content?.id) {
      if (list.eventConfig?.action === 'view') {
        Resync.logEvent({
          eventId: list.event?.eventId || '',
          logId: list.eventConfig?.logId || '',
        });
        if (contentItem?.logAnalytics && list.eventConfig?.logId) {
          contentItem.logAnalytics(list.eventConfig?.logId, {
            itemId: list?.itemId,
            contentViewId: contentItem?.content?.id,
            ...list.eventConfig,
          });
        }
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (!list || !contentItem) return null;
  const listData = list.data as ListProperty;
  const hasData = listData.data && listData.data.length > 0;
  const isHorizontal = listData.styles?.flexDirection === 'row';

  // Get template section (should be 1 section that contains elements or other sections)
  const templateSections = getChildren(list.itemId, contentItem?.content);
  const templateSection = templateSections[0]; // List should have exactly 1 template section

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

  if (!hasData) {
    // Show template preview when no data
    return (
      <View key={`list-${list.itemId}`} style={styles.templatePreview}>
        {templateSection ? (
          <Fragment key={`${templateSection.itemId}-template`}>
            <RenderSection
              section={templateSection}
              contentItem={contentItem}
            />
          </Fragment>
        ) : (
          <Text style={styles.emptyText}>No template section found</Text>
        )}
      </View>
    );
  }

  // Render with FlatList for better performance
  const renderListItem = ({
    item: dataItem,
    index,
  }: {
    item: Record<string, any>;
    index: number;
  }) => {
    return (
      <Pressable onPress={() => handleClick(dataItem)}>
        <View
          style={{
            backgroundColor:
              listData.styles.backgroundColor ||
              listData?.customStyles?.backgroundColor,
            ...getViewStyles(listData.styles),
            ...getViewStyles(listData?.customStyles || {}),
            ...getLayoutStyles(listData.styles, [
              'width',
              'padding',
              'paddingLeft',
              'paddingRight',
              'paddingTop',
              'paddingBottom',
              'margin',
              'marginLeft',
              'marginRight',
              'marginTop',
              'marginBottom',
            ]),
            ...getLayoutStyles(listData?.customStyles || {}, [
              'width',
              'padding',
              'paddingLeft',
              'paddingRight',
              'paddingTop',
              'paddingBottom',
              'margin',
              'marginLeft',
              'marginRight',
              'marginTop',
              'marginBottom',
            ]),
          }}
          {...listData.customProps}
        >
          {templateSection ? (
            <Fragment key={`${templateSection.itemId}-${index}`}>
              <RenderSection
                section={templateSection}
                contentItem={contentItem}
                dataItem={dataItem}
              />
            </Fragment>
          ) : null}
        </View>
      </Pressable>
    );
  };

  return (
    <FlatList
      data={listData.data}
      renderItem={renderListItem}
      horizontal={isHorizontal}
      showsVerticalScrollIndicator={!isHorizontal}
      showsHorizontalScrollIndicator={isHorizontal}
      contentContainerStyle={{
        ...getViewStyles(listData.styles),
        ...getViewStyles(listData?.customStyles || {}),
        ...getLayoutStyles(listData.styles, ['width', 'height']),
        ...getLayoutStyles(listData?.customStyles || {}, ['width', 'height']),
        ...(isHorizontal
          ? {
              columnGap:
                listData.styles.gap || listData?.customStyles?.gap || 0,
            }
          : {
              rowGap: listData.styles.gap || listData?.customStyles?.gap || 0,
            }),
      }}
      scrollEnabled={true}
      bounces={true}
      style={{
        width: listData.styles.width || listData?.customStyles?.width,
        height: listData.styles.height || listData?.customStyles?.height,
      }}
      {...listData.customProps}
    />
  );
};

const styles = StyleSheet.create({
  loadingText: {
    marginTop: 16,
    fontSize: 16,
    color: '#666666',
  },
  errorText: {
    fontSize: 16,
    color: '#FF3B30',
    textAlign: 'center',
    marginBottom: 20,
  },
  retryButton: {
    backgroundColor: '#666666',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 8,
  },
  retryButtonText: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: '600',
  },
  emptyText: {
    color: '#666666',
  },
  text: {
    fontSize: 16,
  },
  buttonText: {
    fontSize: 16,
  },
  iconText: {
    fontSize: 24,
  },
  // List styles
  templatePreview: {
    // padding: 16,
    // marginBottom: 16,
    // backgroundColor: '#f5f5f5',
    // borderRadius: 8,
    // borderWidth: 1,
    // borderColor: '#e0e0e0',
  },
  templateTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 8,
    color: '#666',
  },
  listContainer: {
    marginBottom: 16,
  },
  listTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 12,
    color: '#333',
    paddingHorizontal: 16,
  },
  listContentContainer: {
    // paddingHorizontal: 16,
  },
  listItem: {
    // padding: 12,
    // backgroundColor: '#ffffff',
    // borderRadius: 8,
    // borderWidth: 1,
    // borderColor: '#e0e0e0',
  },
  listItemSeparator: {
    height: 8,
  },
  itemHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
    width: '100%',
  },
  itemLabel: {
    fontSize: 12,
    color: '#666',
  },
  dataBoundBadge: {
    backgroundColor: '#4CAF50',
    paddingHorizontal: 8,
    paddingVertical: 2,
    borderRadius: 12,
  },
  dataBoundText: {
    fontSize: 10,
    color: '#ffffff',
    fontWeight: 'bold',
  },
});
