import { h, type FunctionComponent } from 'preact'
import { useEffect, useState } from 'preact/hooks'
import _ from 'lodash'
import rek from 'rek'
import ObjectTable from './object_table.tsx'
import { Table, Td } from './table.tsx'

const Process: FunctionComponent<{ os?: ANY }> = ({ os }) => {
  const [process, setProcess] = useState<{
    os: Record<string, string | string[]>
    process: Record<string, Record<string, string> | string[]>
  } | null>(null)

  useEffect(() => {
    rek('/api/process').then(setProcess)
  }, [])

  return (
    process && (
      <Table>
        <tbody>
          {Object.entries(process[os ? 'os' : 'process']).map(([key, value]) => (
            <tr key={key}>
              <Td>{key}</Td>
              <Td>
                {Array.isArray(value) ? (
                  value.join(', ')
                ) : _.isPlainObject(value) ? (
                  <ObjectTable object={value} />
                ) : (
                  value
                )}
              </Td>
            </tr>
          ))}
        </tbody>
      </Table>
    )
  )
}

export default Process
