import { memo } from 'react'
import { Heading } from '~/components/heading'
import { CpfCnpj } from '~/components/cpf-cnpj'
import { Table, Tbody, Td, Th, Thead, Tr } from '~/components/table'
import { Abbr } from '~/components/abbr'
import { Datetime } from '~/components/datetime'
import axios from '~/axios'

export function meta({}) {
  return [{ title: 'Usuários' }]
}

export async function clientLoader() {
  await new Promise((r) => setTimeout(r, 2000))
  const index = 'users'
  const { data } = await axios.get('/search/', { params: { index } })
  return data
}

export default function Component({ loaderData: { hits = [] } }) {
  return (
    <>
      <Heading>Usuários</Heading>

      <Table>
        <Thead>
          <Tr>
            <Th>&nbsp;</Th>
            <Th>Nome</Th>
            <Th>CPF/CNPJ</Th>
            <Th>Email</Th>
            <Th>Último acesso</Th>
          </Tr>
        </Thead>
        <Tbody>
          {hits.map((props) => (
            <Row key={props.id} {...props} />
          ))}

          {hits.length === 0 && (
            <Tr className="no-hover">
              <Td colSpan={5}>Nada encontrado</Td>
            </Tr>
          )}
        </Tbody>
      </Table>
    </>
  )
}

const Row = memo(function Row({
  id,
  name,
  cpf,
  cnpj,
  email,
  lastLogin: last_login,
}) {
  return (
    <Tr className="cursor-pointer" data-hover={!cnpj}>
      <Td>
        <Abbr maxLen={6}>{id}</Abbr>
      </Td>
      <Td>
        <Abbr>{name}</Abbr>
      </Td>
      <CpfCnpj as={Td}>{cpf ?? cnpj}</CpfCnpj>
      <Td>
        <Abbr>{email}</Abbr>
      </Td>
      <Datetime as={Td}>{last_login}</Datetime>
    </Tr>
  )
})
