import React, { useCallback, useState } from 'react'
import {
  View,
  Text,
  LayoutChangeEvent,
  StyleSheet,
  StyleProp,
  ViewStyle,
} from 'react-native'
import { IObject } from 'interfaces'
import { sharedStyles } from './styles'
import type { TableColumn } from './TableTypes'
import type { TableTheme } from './theme'
import { useContextHeaderHeight, useContextFixedColumnWidth } from './context'

import TableHeaderBackground from './TableHeaderBackground'
import SortIndicator from './SortIndicator'

type Props = {
  object: IObject
  theme: TableTheme
  fixedFirstColumn: boolean
  columns: TableColumn[]
}

const TableHeader: React.FC<Props> = props => {
  const { columns, theme, fixedFirstColumn, object } = props
  const [backgroundWidth, setBackgroundWidth] = useState(0)
  const { headerHeight, onHeaderHeightChanged } = useContextHeaderHeight(
    object.id
  )
  const fixedContentWidth = useContextFixedColumnWidth(object.id)

  const onLayout = useCallback((event: LayoutChangeEvent) => {
    const { height, width } = event.nativeEvent.layout
    if (height) {
      onHeaderHeightChanged(height)
    }
    if (width) {
      setBackgroundWidth(width)
    }
  }, [])

  const layoutStyles: StyleProp<ViewStyle> = [sharedStyles.header, theme.header]

  if (headerHeight) {
    layoutStyles.push({ height: headerHeight })
  }

  return (
    <View style={layoutStyles} onLayout={onLayout}>
      <TableHeaderBackground
        theme={theme}
        height={headerHeight}
        width={backgroundWidth}
      />
      {columns.map(({ label, style, sort }, index) => {
        const isHiddenFirstColumn = index === 0 && fixedFirstColumn
        const cellStyles: object[] = [sharedStyles.headerCell, style]

        if (isHiddenFirstColumn && fixedContentWidth) {
          cellStyles.push(styles.hidden, { minWidth: fixedContentWidth })
        }

        return (
          <View style={cellStyles} key={label}>
            <Text style={[sharedStyles.headerText, theme.headerText]}>
              {label}
            </Text>
            <SortIndicator theme={theme} direction={sort} />
          </View>
        )
      })}
    </View>
  )
}

const styles = StyleSheet.create({
  hidden: {
    opacity: 0,
  },
})

export default TableHeader
