import React, { HTMLAttributes, memo } from 'react'

export type ComponentProps = HTMLAttributes<HTMLDivElement>

export type GridItemProps = ComponentProps & {
  row: number
  col: number
  rowSpan?: number
  colSpan?: number
}

export const gridDefaultStyle = {
  display: 'grid',
  margin: '8px',
  justifyItems: 'stretch',
  alignItems: 'stretch',
}

export const Grid = memo<ComponentProps>(({ children, style, ...other }) => (
  <div style={{...gridDefaultStyle, ...style}} {...other}>
    {children}
  </div>
))

export const GridItem = memo<GridItemProps>(({ children, row, col, rowSpan, colSpan, style, className, ...other }) => {
  const localRow = +row
  const localCol = +col
  const localColSpan = colSpan ? colSpan - 1 : 0
  const localRowSpan = rowSpan ? rowSpan - 1 : 0
  const gridItemStyle = {
    gridColumnStart: localCol,
    gridColumnEnd: localCol + localColSpan,
    gridRowStart: localRow,
    gridRowEnd: localRow + localRowSpan,
    ...style,
  }

  return (
    <div className={`asb-grid-item ${className || ''}`} style={gridItemStyle} {...other}>
      {children}
    </div>
  )
})

export const Flex = memo<ComponentProps>(({ children, style, ...other }) => (
  <div style={{ display: 'flex', ...style }} {...other}>
    {children}
  </div>
))
