import styles from './index.module.scss';
import cx from '../utils/classname.js';
import type { CSSVariables } from '../utils/types.js';
import { GridProps } from './types.js';
import GridItem from './GridItem/index.js';

const GridComponent = ({
  as: Component = 'div',
  templateColumns,
  templateColumnsMd,
  templateColumnsLg,
  templateRows,
  templateRowsMd,
  templateRowsLg,
  autoFlow = 'row',
  autoFlowMd,
  autoFlowLg,
  autoColumns,
  autoRows,
  justifyContent = 'stretch',
  justifyContentMd,
  justifyContentLg,
  alignItems = 'stretch',
  alignItemsMd,
  alignItemsLg,
  gap,
  gapMd,
  gapLg,
  paddingInline,
  paddingBlock,
  marginInline,
  marginBlock,
  maxWidth,
  maxHeight,
  inline = false,
  className = '',
  style = {},
  children,
}: GridProps) => {
  const defaultClasses = styles.grid;
  const combinedClasses = cx(defaultClasses, className);

  const customStyle: CSSVariables = {
    ...style,
    '--hscl-grid-display': inline ? 'inline-grid' : 'grid',
    '--hscl-grid-autoFlow': autoFlow,
    '--hscl-grid-justifyContent': justifyContent,
    '--hscl-grid-alignItems': alignItems,
  };

  const propertyMap: Record<string, string | undefined> = {
    '--hscl-grid-templateColumns': templateColumns,
    '--hscl-grid-templateColumns-md': templateColumnsMd,
    '--hscl-grid-templateColumns-lg': templateColumnsLg,
    '--hscl-grid-templateRows': templateRows,
    '--hscl-grid-templateRows-md': templateRowsMd,
    '--hscl-grid-templateRows-lg': templateRowsLg,
    '--hscl-grid-autoFlow-md': autoFlowMd,
    '--hscl-grid-autoFlow-lg': autoFlowLg,
    '--hscl-grid-autoColumns': autoColumns,
    '--hscl-grid-autoRows': autoRows,
    '--hscl-grid-gap': gap,
    '--hscl-grid-gap-md': gapMd,
    '--hscl-grid-gap-lg': gapLg,
    '--hscl-grid-justifyContent-md': justifyContentMd,
    '--hscl-grid-justifyContent-lg': justifyContentLg,
    '--hscl-grid-alignItems-md': alignItemsMd,
    '--hscl-grid-alignItems-lg': alignItemsLg,
    '--hscl-grid-maxWidth': maxWidth,
    '--hscl-grid-maxHeight': maxHeight,
    '--hscl-grid-paddingInline': paddingInline,
    '--hscl-grid-paddingBlock': paddingBlock,
    '--hscl-grid-marginInline': marginInline,
    '--hscl-grid-marginBlock': marginBlock,
  };

  // Add style props if they are defined
  Object.entries(propertyMap).forEach(([cssVar, value]) => {
    if (value) {
      customStyle[cssVar] = value;
    }
  });

  return (
    <Component className={combinedClasses} style={customStyle}>
      {children}
    </Component>
  );
};

const Grid = GridComponent as typeof GridComponent;

export default Grid;
export { GridItem };
