import React, { useLayoutEffect, useRef, useState } from 'react'

import styles from './_spreadsheet-pane.module.scss'
import Button from '../Button/Button'
import Icon from '../Icons/Icon'
import LabelAndData from '../LabelAndData/LabelAndData'
import Tooltip from '../Tooltip/Tooltip'
import { type LabelAndDataProps } from '../LabelAndData/LabelAndData'
import ScrollingContainer from '../ScrollingContainer/ScrollingContainer'

export type SpreadsheetPaneProps = {
  /** Text for the header */
  headerText: string
  /** Sub header label and data props */
  subHeader?: LabelAndDataProps
  /** Tooltip info for the info tooltip in the sub header */
  tooltipInfo?: string
  /** Content of the SpreadsheetPane */
  children: ({ collapsed }: { collapsed: boolean }) => React.JSX.Element
  /** Determines if the pane is expanded or collapsed */
  collapsed: boolean
  /** Toggle the collapsed state in the parent */
  setCollapsed: (collapsed: boolean) => void
  /** Optional prop to add a test id to the SpreadsheetPane for QA testing */
  qaTestId?: string
}

const SpreadsheetPane = ({
  headerText,
  subHeader,
  tooltipInfo,
  children,
  collapsed,
  setCollapsed,
  qaTestId = 'spreadsheet-pane',
}: SpreadsheetPaneProps): React.JSX.Element => {
  const spreadsheetPaneContainerRef = useRef<HTMLDivElement>(null)
  const subHeaderRef = useRef<HTMLDivElement>(null)
  const [contentHeight, setContentHeight] = useState(0)

  useLayoutEffect(() => {
    const calculateAndSetHeight = () => {
      if (
        spreadsheetPaneContainerRef.current &&
        spreadsheetPaneContainerRef.current.parentElement
      ) {
        const containerHeight =
          spreadsheetPaneContainerRef.current.parentElement?.clientHeight ?? 0
        const subHeaderHeight = subHeaderRef.current?.clientHeight ?? 0
        const headerHeight = 56

        const newContentHeight =
          containerHeight - subHeaderHeight - headerHeight - 8

        setContentHeight(newContentHeight > 0 ? newContentHeight : 0)
      }
    }
    calculateAndSetHeight()

    const handleResize = () => {
      calculateAndSetHeight()
    }

    window.addEventListener('resize', handleResize)

    return () => {
      window.removeEventListener('resize', handleResize)
    }
  }, [collapsed, subHeader])

  return (
    <div
      className={`${styles.container} ${
        collapsed ? styles.collapsed : styles.expanded
      }`}
      ref={spreadsheetPaneContainerRef}
      qa-test-id={qaTestId}
    >
      <div className={styles.header}>
        {!collapsed ? <span>{headerText}</span> : null}
        <Button as='unstyled' onClick={() => setCollapsed(!collapsed)}>
          <Icon
            icon='caretRight'
            className={`${styles.arrowIcon} ${collapsed ? styles.flipped : ''}`}
            color='dark-blue'
          />
        </Button>
      </div>
      {subHeader || tooltipInfo ? (
        <div
          className={`${
            subHeader ? styles.subHeader : styles.withoutSubHeader
          }`}
          ref={subHeaderRef}
        >
          {subHeader && !collapsed ? <LabelAndData {...subHeader} /> : null}
          {tooltipInfo ? (
            <Tooltip tooltipContent={tooltipInfo} position='left'>
              <Icon icon='info' color='dark-blue' />
            </Tooltip>
          ) : null}
        </div>
      ) : null}
      {subHeader || tooltipInfo ? (
        <div className={`${styles.divider}`} />
      ) : null}
      <ScrollingContainer height={contentHeight} hideGradients={true}>
        {children({ collapsed })}
      </ScrollingContainer>
    </div>
  )
}

const ContentBlock = ({
  children,
}: {
  children: React.ReactNode
}): React.JSX.Element => {
  return <div className={styles.contentBlock}>{children}</div>
}

const LargeAlert = ({
  children,
  color,
}: {
  children: React.ReactNode
  color: 'pink' | 'blue' | 'green' | 'red'
}) => {
  return (
    <div className={`${styles.largeAlert} ${styles[color]}`}>{children}</div>
  )
}

SpreadsheetPane.ContentBlock = ContentBlock
SpreadsheetPane.LargeAlert = LargeAlert

export { SpreadsheetPane }
