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

const GridItemComponent = <C extends React.ElementType = 'div'>({
  as,
  gridColumn,
  gridColumnMd,
  gridColumnLg,
  gridRow,
  gridRowMd,
  gridRowLg,
  justifySelf,
  justifySelfMd,
  justifySelfLg,
  alignSelf,
  alignSelfMd,
  alignSelfLg,
  className = '',
  style = {},
  children,
  ...rest
}: GridItemProps<C>) => {
  const Component = as || 'div';
  const defaultClasses = styles.gridItem;
  const combinedClasses = cx(defaultClasses, className);

  const customStyle: CSSVariables = {
    ...style,
  };

  const propertyMap: Record<string, string | undefined> = {
    '--hs-gridItem-gridColumn': gridColumn,
    '--hs-gridItem-gridColumn-md': gridColumnMd,
    '--hs-gridItem-gridColumn-lg': gridColumnLg,
    '--hs-gridItem-gridRow': gridRow,
    '--hs-gridItem-gridRow-md': gridRowMd,
    '--hs-gridItem-gridRow-lg': gridRowLg,
    '--hs-gridItem-justifySelf': justifySelf,
    '--hs-gridItem-justifySelf-md': justifySelfMd,
    '--hs-gridItem-justifySelf-lg': justifySelfLg,
    '--hs-gridItem-alignSelf': alignSelf,
    '--hs-gridItem-alignSelf-md': alignSelfMd,
    '--hs-gridItem-alignSelf-lg': alignSelfLg,
  };

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

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

const GridItem = GridItemComponent as typeof GridItemComponent;

export default GridItem;
