import { useMemo } from 'react'
import type { ColumnDef } from '@tanstack/react-table'
import { Badge } from '@/components/ui/badge'
import { DataTable } from '@/components/ui/data-table'
import type { UserListItem } from '../types'
import { formatInstantOrDash } from '@/lib/dateFormat'

interface UsersTableProps {
  rows: UserListItem[]
  onRowClick: (user: UserListItem) => void
}

export function UsersTable({ rows, onRowClick }: UsersTableProps) {
  const columns = useMemo<ColumnDef<UserListItem>[]>(
    () => [
      {
        accessorKey: 'username',
        header: 'Usuario',
        cell: ({ row }) => (
          <span className="font-mono text-xs">{row.original.username}</span>
        ),
        meta: { priority: 'high' },
      },
      {
        id: 'fullName',
        header: 'Nombre',
        cell: ({ row }) => `${row.original.nombre} ${row.original.apellido}`,
        meta: { priority: 'high' },
      },
      {
        accessorKey: 'rol',
        header: 'Rol',
        cell: ({ row }) => (
          <Badge variant="secondary" className="capitalize">
            {row.original.rol}
          </Badge>
        ),
        meta: { priority: 'high' },
      },
      {
        accessorKey: 'activo',
        header: 'Estado',
        cell: ({ row }) =>
          row.original.activo ? (
            <Badge
              variant="secondary"
              className="bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"
            >
              Activo
            </Badge>
          ) : (
            <Badge
              variant="secondary"
              className="bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"
            >
              Inactivo
            </Badge>
          ),
        meta: { priority: 'medium' },
      },
      {
        accessorKey: 'email',
        header: 'Email',
        cell: ({ row }) => (
          <span className="text-muted-foreground">
            {row.original.email ?? '—'}
          </span>
        ),
        meta: { priority: 'medium' },
      },
      {
        accessorKey: 'ultimoLogin',
        header: 'Último login',
        cell: ({ row }) => (
          <span className="text-muted-foreground">
            {formatInstantOrDash(row.original.ultimoLogin)}
          </span>
        ),
        meta: { priority: 'low' },
      },
    ],
    [],
  )

  return (
    <DataTable
      columns={columns}
      data={rows}
      onRowClick={onRowClick}
      getRowId={(row) => String(row.id)}
      emptyMessage="Sin resultados — no se encontraron usuarios con los filtros seleccionados."
    />
  )
}
