import Link from "next/link"
import PageHeader from "@/components/app/PageHeader"
import PageShell from "@/components/app/PageShell"
import { Button } from "@/components/ui/button"
import LeaveTabView from "@/features/leave/components/LeaveTabView"
import { type PublicHoliday } from "@/features/leave/components/Calendar"
import { listLeaveRequests, listPublicHolidays } from "@/features/leave/service"
import { auth } from "@/lib/auth"
import { userCanProcessLeave } from "@/lib/leave-approval"
import { db } from "@/lib/db"

export const dynamic = "force-dynamic"

export default async function LeavePage() {
  const session = await auth()
  const currentUserId = session?.user?.id
  const canProcessLeave = currentUserId
    ? await userCanProcessLeave(currentUserId)
    : false

  const [requests, holidays, branches] = await Promise.all([
    listLeaveRequests(currentUserId),
    listPublicHolidays(),
    db.branch.findMany({ select: { id: true, name: true }, orderBy: { name: "asc" } }),
  ])


  const serializedHolidays: PublicHoliday[] = holidays.map((h: any) => ({
    id: h.id,
    name: h.name,
    date: h.date.toISOString().split("T")[0],
    endDate: h.endDate ? h.endDate.toISOString().split("T")[0] : undefined,
    type: h.type as PublicHoliday["type"],
    description: h.description ?? undefined,
  }))

  return (
    <PageShell>
      <PageHeader
        title="Leave"
        description="Manage employee leave applications and view the leave calendar."
        actions={
          <Button asChild>
            <Link href="/leave/create">Add Leave Request</Link>
          </Button>
        }
      />
      <LeaveTabView
        requests={requests}
        holidays={serializedHolidays}
        branches={branches}
        canManage={true}
        canProcessLeave={canProcessLeave}
      />
    </PageShell>
  )
}