import { h, type FunctionComponent } from 'preact'
import { Table, Th, type onSortByFunction } from './table.tsx'
import type { Selectable } from 'kysely'

import type { User, Role } from '../../../shared/types.db.ts'

const UsersTable: FunctionComponent<{
  users: (Selectable<User> & { roles?: Role[] })[]
  onSortBy: onSortByFunction
}> = ({ users, onSortBy }) => (
  <Table onSortBy={onSortBy}>
    <thead>
      <tr>
        <Th sort='id'>ID</Th>
        <Th sort>Email</Th>
        <Th>Roles</Th>
        <Th sort='emailVerifiedAt'>Email Verified</Th>
        <Th sort='lastLoginAt'>Last Login</Th>
        <Th sort>Login Attempts</Th>
        <Th sort='lastLoginAttemptAt'>Last Login Attempt</Th>
      </tr>
    </thead>
    <tbody>
      {users?.length ? (
        users.map((user) => (
          <tr key={user.id}>
            <td>{user.id}</td>
            <td>{user.email}</td>
            <td>{user.roles?.map((role) => role.name).join(', ')}</td>
            <td>{user.emailVerifiedAt}</td>
            <td>{user.lastLoginAt}</td>
            <td>{user.loginAttempts}</td>
            <td>{user.lastLoginAttemptAt}</td>
          </tr>
        ))
      ) : (
        <tr>
          <td colSpan={7}>No users found</td>
        </tr>
      )}
    </tbody>
  </Table>
)

export default UsersTable
