import type { Route } from './+types/route'

import { Suspense } from 'react'
import { Await } from 'react-router'

import { DateTime } from '@repo/ui/components/datetime'
import { Skeleton } from '@repo/ui/components/skeleton'
import { Card, CardContent } from '@repo/ui/components/ui/card'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from '@repo/ui/components/ui/table'
import { request as req } from '@repo/util/request'

export function meta({}) {
  return [{ title: 'Certificações' }]
}

export async function loader({ context, request, params }: Route.LoaderArgs) {
  const { searchParams } = new URL(request.url)

  const month =
    searchParams.get('month') || new Date().toISOString().slice(0, 10)
  const reporting = req({
    url: `/orgs/${params.orgid}/enrollments/certs?month=${month}`,
    context,
    request
  }).then((r) => r.json())

  return {
    reporting
  }
}

export default function Route({
  loaderData: { reporting }
}: Route.ComponentProps) {
  return (
    <Suspense fallback={<Skeleton />}>
      <div className="space-y-0.5 mb-8">
        <h1 className="text-2xl font-bold tracking-tight">
          Gerenciar certificações
        </h1>
        <p className="text-muted-foreground">
          Centralize o controle das certificações dos colaboradores e acompanhe
          prazos e renovações com facilidade.
        </p>
      </div>

      <Card>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow className=" pointer-events-none">
                <TableHead>Colaborador</TableHead>
                <TableHead>Curso</TableHead>
                <TableHead>Matriculado em</TableHead>
                <TableHead>Concluído em</TableHead>
                <TableHead>Cert. válido até</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              <Await resolve={reporting}>
                {({ items = [] }) => {
                  return (
                    <>
                      {items.map(
                        (
                          {
                            course,
                            user,
                            enrolled_at,
                            completed_at,
                            expires_at
                          },
                          idx
                        ) => {
                          return (
                            <TableRow key={idx}>
                              <TableCell>{user.name}</TableCell>
                              <TableCell>{course.name}</TableCell>
                              <TableCell>
                                <DateTime>{enrolled_at}</DateTime>
                              </TableCell>
                              <TableCell>
                                <DateTime>{completed_at}</DateTime>
                              </TableCell>
                              <TableCell>
                                <DateTime>{expires_at}</DateTime>
                              </TableCell>
                            </TableRow>
                          )
                        }
                      )}

                      {items.length === 0 && (
                        <TableRow className="pointer-events-none">
                          <TableCell className="h-24 text-center" colSpan={5}>
                            Nenhum resultado.
                          </TableCell>
                        </TableRow>
                      )}
                    </>
                  )
                }}
              </Await>
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </Suspense>
  )
}
