import { h, type FunctionComponent } from 'preact'
// eslint-disable-next-line import/no-unresolved
// @ts-ignore
import Format from 'easy-tz/format'
// @ts-ignore
import suppress from '@domp/suppress'

import Button from './button.tsx'
import { Table, Th } from './table.tsx'
import s from './errors_table.module.scss'

const format = Format.bind(null, null, 'YYYY.MM.DD\nHH:mm:ss')

const ErrorsTable: FunctionComponent<{
  defaultSort: string
  errors: ANY[]
  onDelete?: ANY
  onSelect?: ANY
  onSortBy?: ANY
  pending?: boolean
}> = ({ defaultSort, errors, onDelete, onSelect, onSortBy, pending }) => {
  return (
    <Table className={s.base} defaultSort={defaultSort} onSortBy={onSortBy}>
      <thead>
        <tr>
          <Th sort='id'>ID</Th>
          <Th sort>CreatedAt</Th>
          <Th sort='statusCode'>Status</Th>
          <Th sort>Type</Th>
          <Th sort>Message</Th>
          <Th sort>Method</Th>
          <Th sort>Path</Th>
          <Th sort='ip'>IP</Th>
          <Th sort>ReqId</Th>
          <th />
        </tr>
      </thead>
      <tbody>
        {errors?.length ? (
          errors.map((error) => (
            <tr key={error.id} onClick={() => onSelect(error.id)}>
              <td className={s.id}>{error.id}</td>
              <td>{format(error.createdAt)}</td>
              <td className={s.statusCode}>{error.statusCode}</td>
              <td>{error.type}</td>
              <td>{error.message.slice(0, 255)}</td>
              <td className={s.method}>{error.method}</td>
              <td className={s.path}>{error.path}</td>
              <td>{error.ip}</td>
              <td className={s.reqId}>{error.reqId}</td>
              <td className={s.controls}>
                <Button
                  size='small'
                  disabled={pending}
                  color='red'
                  onClick={(e) => {
                    suppress(e)
                    onDelete(error.id)
                  }}
                >
                  Delete
                </Button>
              </td>
            </tr>
          ))
        ) : (
          <tr>
            <td colSpan={6}>No errors found</td>
          </tr>
        )}
      </tbody>
    </Table>
  )
}

export default ErrorsTable
