// app/admin/[entity]/page.tsx
import Link from "next/link"
import { getServerSession } from "next-auth"
import { redirect } from "next/navigation"
import { authOptions } from "@/lib/auth"

import { ProfileDropdown } from "@/components/profile-dropdown"
import { Header } from "@/components/header"
import { Main } from "@/components/main"
import { ThemeSwitch } from "@/components/theme-switch"

import { TasksProvider } from "../components/tasks-provider"
import { TasksTable } from "../components/tasks-table"

import { getHotels } from "@/services/hotels"
import { getCabs } from "@/services/cabs"
import { notFound } from "next/navigation"

import { TasksPrimaryButtons } from "../components/tasks-primary-buttons"
import { getFields } from "@/services/myfields"

export default async function AdminListPage({
  params,
  searchParams,
}: {
  params: Promise<{ entity: string }>
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
  const sParams = await searchParams

  const page = Number(sParams.page) || 1
  const pageSize = Number(sParams.pageSize) || 10
  const filter = typeof sParams.filter === "string" ? sParams.filter : ""

  let responseData: { data: any[]; totalCount: number } = {
    data: [],
    totalCount: 0,
  }

  responseData = await getFields({ page, pageSize, filter })

  const entity = "myfields"
  const session = await getServerSession(authOptions)

  if (!session) {
    redirect("/auth/sign-in")
  }

  return (
    <TasksProvider>
      {/* ===== Top Heading ===== */}
      <Header>
        <h2 className="text-lg font-semibold">
          {entity.charAt(0).toUpperCase() + entity.slice(1)}
        </h2>

        <div className="ms-auto flex items-center space-x-4">
          <ThemeSwitch />
          <ProfileDropdown />
        </div>
      </Header>

      {/* ===== Main ===== */}
      <Main className="flex flex-1 flex-col gap-4 sm:gap-6">
        <div className="flex flex-wrap items-end justify-between gap-2">
          <div>
            <h2 className="text-2xl font-bold tracking-tight">
              {entity.charAt(0).toUpperCase() + entity.slice(1)} List
            </h2>
            <p className="text-muted-foreground">
              Here&apos;s a list of your {entity} with their details and actions
              you can perform on them.
            </p>
          </div>

          <TasksPrimaryButtons type={entity} />
        </div>
        <TasksTable
          data={responseData.data}
          totalCount={responseData.totalCount}
          entity={entity}
        />
      </Main>
    </TasksProvider>
  )
}
