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,
    '--hs-grid-autoFlow': autoFlow,
    '--hs-grid-justifyContent': justifyContent,
    '--hs-grid-alignItems': alignItems,
    ...(inline ? { display: 'inline-grid' } : {}),
    ...(autoColumns ? { gridAutoColumns: autoColumns } : {}),
    ...(autoRows ? { gridAutoRows: autoRows } : {}),
    ...(paddingInline ? { paddingInline } : {}),
    ...(paddingBlock ? { paddingBlock } : {}),
    ...(marginInline ? { marginInline } : {}),
    ...(marginBlock ? { marginBlock } : {}),
    ...(maxWidth ? { maxWidth } : {}),
    ...(maxHeight ? { maxHeight } : {}),
  };

  const propertyMap: Record<string, string | undefined> = {
    '--hs-grid-templateColumns': templateColumns,
    '--hs-grid-templateColumns-md': templateColumnsMd,
    '--hs-grid-templateColumns-lg': templateColumnsLg,
    '--hs-grid-templateRows': templateRows,
    '--hs-grid-templateRows-md': templateRowsMd,
    '--hs-grid-templateRows-lg': templateRowsLg,
    '--hs-grid-autoFlow-md': autoFlowMd,
    '--hs-grid-autoFlow-lg': autoFlowLg,
    '--hs-grid-gap': gap,
    '--hs-grid-gap-md': gapMd,
    '--hs-grid-gap-lg': gapLg,
    '--hs-grid-justifyContent-md': justifyContentMd,
    '--hs-grid-justifyContent-lg': justifyContentLg,
    '--hs-grid-alignItems-md': alignItemsMd,
    '--hs-grid-alignItems-lg': alignItemsLg,
  };

  // 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 };
