import PaginationButtons from "@/components/common/pagination"
import { formatDate } from "@/lib/utils"
import { MovementService } from "@/services/movement.service"

export default async function MovementsPage(props: {
  searchParams?: Promise<{
    page?: string
  }>
}) {
  const searchParams = await props.searchParams
  const currentPage = searchParams?.page ? parseInt(searchParams.page) : 1
  const { data: movements, totalPages } = await MovementService.findAll({
    page: currentPage,
    pageSize: 12,
  })

  return (
    <div className="flex flex-col gap-4">
      <div className="flex items-center justify-between gap-4">
        <h1 className="text-2xl font-bold">Movements</h1>
      </div>
      {movements.length === 0 && <div>No movements found</div>}
      {movements.length > 0 && (
        <div className="overflow-x-auto">
          <table className="text-muted-foreground w-full text-left text-sm">
            <thead className="border-b">
              <tr>
                <th scope="col" className="p-4">
                  Type
                </th>
                <th scope="col" className="p-4">
                  Item
                </th>
                <th scope="col" className="p-4">
                  Serial Number
                </th>
                <th scope="col" className="p-4">
                  Quantity
                </th>
                <th scope="col" className="p-4">
                  Recipient
                </th>
                <th scope="col" className="p-4">
                  Date
                </th>
              </tr>
            </thead>
            <tbody>
              {movements.map((movement) => (
                <tr key={movement.id} className="border-b">
                  <td className="p-4">{movement.type}</td>
                  <td className="p-4">{movement?.item?.name}</td>
                  <td className="p-4">
                    {movement?.asset?.serialNumber || "-"}
                  </td>
                  <td className="p-4">{movement.quantity}</td>
                  <td className="p-4">
                    {movement?.recipient?.firstName || "-"}{" "}
                    {movement?.recipient?.lastName || "-"}
                  </td>
                  <td className="p-4">{formatDate(movement.createdAt)}</td>
                </tr>
              ))}
            </tbody>
            <tfoot className="border-t">
              <tr>
                <td colSpan={6} className="p-4 text-center text-sm">
                  <PaginationButtons totalPages={totalPages} />
                </td>
              </tr>
            </tfoot>
          </table>
        </div>
      )}
    </div>
  )
}
