import { Box } from '@mui/material'

function tableToJson(innerText) {
  if (!innerText) return []
  const matrix = innerText
    ?.split('\n')
    ?.map((row) => row?.split('\t')?.map((cell) => (cell === '' ? null : cell)))

  const arrayList = matrix.filter((row) => row.length === matrix[0].length)

  var data = []
  for (var i = 1; i < arrayList.length; i++) {
    var tableRow = arrayList[i]
    let rowObj = {}
    for (var j = 0; j < arrayList[0].length; j++) {
      rowObj[arrayList[0][j]] = tableRow[j]
    }
    data.push(rowObj)
  }
  return data
}

export default function ExcelToJsonInput({ onChange }) {
  return (
    <Box
      onInput={(e) => {
        const input = e.currentTarget.innerText
        let json = tableToJson(input)
        onChange(json)
      }}
      contentEditable
      sx={{
        fontSize: '16px',
        height: 'auto',
        width: '100%',
        border: '1px solid #ccc',
        color: 'black',
        padding: '20px',
        '& table': {
          borderCollapse: 'collapse',
          border: '1px solid #ccc',
          '& th, & td': {
            border: '1px solid #ccc !important',
            padding: '5px',
            background: 'white !important',
            fontSize: '14px',
          },
          '& font': {
            fontSize: '14px',
            fontFamily: 'sans-serif',
          },
        },
      }}
    />
  )
}
