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> = {
    '--hscl-gridItem-gridColumn': gridColumn,
    '--hscl-gridItem-gridColumn-md': gridColumnMd,
    '--hscl-gridItem-gridColumn-lg': gridColumnLg,
    '--hscl-gridItem-gridRow': gridRow,
    '--hscl-gridItem-gridRow-md': gridRowMd,
    '--hscl-gridItem-gridRow-lg': gridRowLg,
    '--hscl-gridItem-justifySelf': justifySelf,
    '--hscl-gridItem-justifySelf-md': justifySelfMd,
    '--hscl-gridItem-justifySelf-lg': justifySelfLg,
    '--hscl-gridItem-alignSelf': alignSelf,
    '--hscl-gridItem-alignSelf-md': alignSelfMd,
    '--hscl-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;
