import styled, { CSSObject } from '@emotion/styled'
import {
  Table,
  TableCell,
  TableContainer,
  TableRow,
  Theme,
  alpha,
} from '@mui/material'
import { SxProps } from '@mui/system'
import _ from 'lodash'
import {
  StyledCellProps,
  StyledMuiTableProps,
  StyledTableContainerProps,
} from './interface'

export const StyledTableCell = styled(TableCell)<StyledCellProps>(
  ({
    theme,
    columnsLength,
    columnIndex,
    rowIndex,
    col,
    sx,
    isBodyCell = false,
    isHeaderCell = false,
  }) => {
    const { rowkey, columnKey, cellKey, allKey } = getSxKeys(
      rowIndex,
      columnIndex,
    )
    const rowSx: SxProps<Theme> = _.get(sx, rowkey)
    const columnSx: SxProps<Theme> = _.get(sx, columnKey)
    const cellSx: SxProps<Theme> = _.get(sx, cellKey)
    const allSx: SxProps<Theme> = _.get(sx, allKey)
    return {
      ...(col?.width && {
        width: col?.width,
      }),
      ['@media(max-width: 680px)']: {
        borderRightColor:
          columnsLength - 1 !== columnIndex ? '#1212121A' : 'none',
        borderRightStyle: columnsLength - 1 !== columnIndex ? 'solid' : 'none',
      },

      ...(isBodyCell && {
        color: col.textColor,
        padding: '15px',
        font: 'avenir',
        fontSize: '14px',
      }),
      ...(isHeaderCell && {
        fontWeight: 600,
        fontSize: '14px',
      }),

      ...columnSx,
      ...rowSx,
      ...cellSx,
      ...allSx,
    } as CSSObject
  },
)

export const StyledMuiTable = styled(Table)<StyledMuiTableProps>(
  ({ theme, sx }) => {
    const containerSx: SxProps<Theme> = _.get(sx, 'MuiTable')
    return {
      ...containerSx,
    } as CSSObject
  },
)

export const StyledTableRow = styled(TableRow, {
  shouldForwardProp: (prop) => prop !== 'canRowClick',
})<{ canRowClick: boolean }>(({ canRowClick }) => ({
  ...(canRowClick && {
    cursor: 'pointer',
    '&.MuiTableRow-hover:hover': {
      backgroundColor: alpha('#f2f2f2', 0.4),
    },
  }),
}))

export const StyledTableContainer = styled(
  TableContainer,
)<StyledTableContainerProps>(({ theme, sx }) => {
  const containerSx: SxProps<Theme> = _.get(sx, 'TableContainer')

  return {
    width: '100%',
    overflowX: 'auto',
    ...containerSx,
  } as CSSObject
})

const getSxKeys = (rowIndex, columnIndex) => {
  return {
    rowkey: `row:${rowIndex}`,
    columnKey: `column:${columnIndex}`,
    cellKey: `row:${rowIndex},column:${columnIndex}`,
    allKey: 'Tablecell',
  }
}
