import type { Column } from '@tanstack/react-table'

import type { CellPosition, RowHeightValue } from '@components/ui/data-grid/data-grid-types'

export function getCellKey(rowIndex: number, columnId: string) {
  return `${rowIndex}:${columnId}`
}

export function parseCellKey(cellKey: string): Required<CellPosition> {
  const parts = cellKey.split(':')
  const rowIndexStr = parts[0]
  const columnId = parts[1]
  if (rowIndexStr && columnId) {
    const rowIndex = parseInt(rowIndexStr, 10)
    if (!Number.isNaN(rowIndex)) {
      return { rowIndex, columnId }
    }
  }
  return { rowIndex: 0, columnId: '' }
}

export function getRowHeightValue(rowHeight: RowHeightValue): number {
  // TODO: find a way to use the css variable directly (currently the style might not be loaded yet which would lead to wrong numbers)
  const lineHeight = /* Number.parseFloat(
    getComputedStyle(document.documentElement)
      .getPropertyValue('--line-height-sm')
      .trim()
      .replaceAll(/[^\d.-]/g, ''),
  ) */ 16
  /* const rowHeightMap: Record<RowHeightValue, number> = {
    short: lineHeight * getLineCount(rowHeight) + 12,
    medium: lineHeight * getLineCount(rowHeight) + 12,
    tall: lineHeight * getLineCount(rowHeight) + 12,
    'extra-tall': lineHeight * getLineCount(rowHeight) + 12,
  } */

  return /* rowHeightMap[rowHeight] */ lineHeight * getLineCount(rowHeight) + 12
}

export function getLineCount(rowHeight: RowHeightValue): number {
  const lineCountMap: Record<RowHeightValue, number> = {
    short: 1,
    medium: 2,
    tall: 3,
    'extra-tall': 4,
  }

  return lineCountMap[rowHeight]
}

export function getCommonPinningStyles<TData>({
  column,
  withBorder = false,
}: {
  column: Column<TData>
  withBorder?: boolean
}): React.CSSProperties {
  const isPinned = column.getIsPinned()
  const isLastLeftPinnedColumn = isPinned === 'left' && column.getIsLastColumn('left')
  const isFirstRightPinnedColumn = isPinned === 'right' && column.getIsFirstColumn('right')

  return {
    boxShadow: withBorder
      ? isLastLeftPinnedColumn
        ? '-4px 0 4px var(--border) inset'
        : isFirstRightPinnedColumn
          ? '4px 0 -4px var(--border) inset'
          : undefined
      : undefined,
    left: isPinned === 'left' ? `${column.getStart('left')}px` : undefined,
    right: isPinned === 'right' ? `${column.getAfter('right')}px` : undefined,
    opacity: isPinned ? 0.97 : 1,
    position: isPinned ? 'sticky' : 'relative',
    background: isPinned ? 'var(--background)' : 'var(--background)',
    width: column.getSize(),
    zIndex: isPinned ? 1 : undefined,
  }
}
