import React from 'react'

import { useWindowSize } from '../../../hooks/useWindowSize/useWindowSize'

type SpreadsheetSizerProps = {
  children: ({
    width,
    height,
  }: {
    width: number
    height: number
  }) => React.ReactNode
  customWidth?: number
  customHeight?: number
  /** If the table is next to another element, the computed width of the table will be incorrect. Use this to input the width of the element (including padding, margin, and other spacing) to have the correct width for the table. */
  widthOffset?: number
  /** Optional prop to add a test id to the SpreadsheetContainer for QA testing */
  qaTestId?: string
}

const SpreadsheetSizer = ({
  children,
  customWidth,
  customHeight,
  widthOffset = 0,
  qaTestId,
}: SpreadsheetSizerProps): React.JSX.Element => {
  const containerDimensions = useWindowSize()
  const standardWidth =
    (containerDimensions.width ?? 0) -
    widthOffset -
    40 /* Magic number to account for padding of the .app-content-layout container*/
  const standardHeight = containerDimensions.height ?? 0
  const width = customWidth ?? standardWidth
  const height = customHeight ? customHeight : standardHeight
  const style: React.CSSProperties = {
    width,
    height: standardHeight,
  }
  return (
    containerDimensions && (
      <div style={style} qa-test-id={qaTestId}>
        {children({ width, height })}
      </div>
    )
  )
}

export default SpreadsheetSizer
