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

export interface CardProps extends ViewProps {
  /**
   * Optional. Background image for the card.
   */
  backgroundImage?: string;

  /**
   * Optional. Use shadow for the card.
   */
  useShadow?: boolean;
}

const Card: React.FC<CardProps> = ({
  children,
  style,
  backgroundImage,
  useShadow = false,
  ...props
}) => {
  const { showGrid, theme } = useContext(ApplicationContext);
  const { numberOfColumns } = useGridSystem();

  const gutterSize = 8;
  const margin = 12;
  const widthSection = Dimensions.get('window').width - margin * 2;
  let sizePerSpan =
    (widthSection - margin * 2 - gutterSize * (numberOfColumns - 1)) /
      numberOfColumns -
    1 / numberOfColumns;

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

  /**
   * render overlay only dev mode
   */
  const renderOverlay = () => {
    return (
      <>
        <GridSystem
          width={widthSection}
          gutterSize={Spacing.S}
          screenGrid={false}
          gridColor={Colors.red_01}
        />
        <View pointerEvents={'none'} style={styles.boxGridCard} />
      </>
    );
  };

  return (
    <GridContext.Provider value={gridContext}>
      <View
        {...props}
        onLayout={undefined}
        style={[
          { backgroundColor: theme.colors.background.surface },
          style,
          styles.protectedStyle,
          styles.card,
          {
            width: widthSection,
            marginHorizontal: margin,
            gap: gutterSize,
          },
          !!backgroundImage && { backgroundColor: undefined },
          useShadow && Shadow.Light,
        ]}
      >
        {!!backgroundImage && (
          <Image
            source={{ uri: backgroundImage }}
            style={[
              styles.imageBackground,
              {
                width: widthSection,
                borderRadius: Radius.M,
              },
            ]}
          />
        )}
        {/* Render only allowed children as valid React elements */}
        {children}
        {showGrid && renderOverlay()}
      </View>
    </GridContext.Provider>
  );
};

Card.displayName = 'Card';

export default Card;
