import React, { useContext } from 'react';
import { Dimensions, View, ViewProps } from 'react-native';
import { useGridSystem } from './utils';
import { GridContextProps } from './types';
import { GridContext } from './index';
import { ApplicationContext, MiniAppContext } from '../Context';
import styles from './styles';
import { Image } from '../Image';
import { Spacing } from '../Consts';

export interface SectionProps extends ViewProps {
  /**
   * Optional. If `true`, the Section component will be displayed in an expanded state.
   * Defaults to `false` if not provided.
   */
  expanded?: boolean;

  /**
   * Optional. If `true`, margin will be applied to the Section component.
   * Defaults to `false` if not provided.
   */
  useMargin?: boolean;

  /**
   * Optional. Background image for the Section component.
   */
  backgroundImage?: string;
}

const Section: React.FC<SectionProps> = ({
  children,
  useMargin = true,
  backgroundImage,
  style,
  ...props
}) => {
  const { showGrid } = useContext(ApplicationContext);
  const { numberOfColumns } = useGridSystem();

  const gutterSize = 12;
  let margin = 0;
  if (useMargin) {
    margin = 12;
  }
  let widthSection = Dimensions.get('window').width;
  if (useMargin) {
    widthSection = widthSection - margin * 2;
  }

  const sizePerSpan =
    (widthSection - (numberOfColumns - 1) * gutterSize) / numberOfColumns;

  const gridContext: GridContextProps = {
    numberOfColumns,
    gutterSize: Spacing.M,
    sizePerSpan,
    getSizeSpan: span => {
      return span * sizePerSpan + gutterSize * (span - 1);
    },
  };

  /**
   * render overlay only dev mode
   */
  const renderOverlay = () => {
    return <View pointerEvents={'none'} style={styles.boxGridSection} />;
  };

  return (
    <GridContext.Provider value={gridContext}>
      <View
        {...props}
        onLayout={undefined}
        style={[
          style,
          styles.protectedStyle,
          {
            width: widthSection,
            marginHorizontal: margin,
            flexDirection: 'row',
            flexWrap: 'wrap',
            gap: gutterSize,
          },
        ]}
      >
        {!!backgroundImage && (
          <Image
            source={{ uri: backgroundImage }}
            style={styles.imageBackground}
          />
        )}
        {/* Render only allowed children as valid React elements */}
        {children}
        {showGrid && renderOverlay()}
      </View>
    </GridContext.Provider>
  );
};

Section.displayName = 'Section';

export default Section;
