import { Pencil } from "lucide-react"
import Link from "next/link"

import PageHeader from "@/components/common/pageheader"
import PaginationButtons from "@/components/common/pagination"
import { Button } from "@/components/ui/button"
import { AssetService } from "@/services/asset.service"

export default async function AssetsPage(props: {
  searchParams?: Promise<{
    page?: string
    search?: string
  }>
}) {
  const searchParams = await props.searchParams
  const currentPage = searchParams?.page ? parseInt(searchParams.page) : 1
  const search = searchParams?.search || ""
  const { data: assets, totalPages } =
    await AssetService.findAllWithItemAndCategory({
      page: currentPage,
      pageSize: 10,
      search,
    })

  return (
    <div className="flex flex-col gap-4">
      <PageHeader
        title="Assets"
        link="/inventory/assets/new"
        data={assets}
        search={search}
      />
      {assets.length === 0 && currentPage === 1 && (
        <div className="flex gap-4">
          <div className="flex items-center justify-between gap-4">
            No Assets found.
          </div>
        </div>
      )}
      {assets.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">
                  Item Name
                </th>
                <th scope="col" className="p-4">
                  Category
                </th>
                <th scope="col" className="p-4">
                  Serial Number
                </th>
                <th scope="col" className="p-4">
                  Status
                </th>
                <th scope="col" className="p-4">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody>
              {assets.map((asset) => (
                <tr key={asset.id} className="border-b">
                  <td className="p-4">{asset.item?.name}</td>
                  <td className="p-4">{asset.item?.category?.name}</td>
                  <td className="p-4">{asset.serialNumber}</td>
                  <td className="p-4">{asset.status}</td>
                  <td className="flex items-center gap-2 p-4">
                    <Link href={`/inventory/assets/${asset.id}/edit`} passHref>
                      <Button variant="outline" size="icon">
                        <Pencil />
                      </Button>
                    </Link>
                  </td>
                </tr>
              ))}
            </tbody>
            <tfoot className="border-t">
              <tr>
                <td colSpan={5} className="p-4 text-center text-sm">
                  <PaginationButtons totalPages={totalPages} />
                </td>
              </tr>
            </tfoot>
          </table>
        </div>
      )}
    </div>
  )
}
