import Link from "next/link"
import { Button } from "@/components/ui/button"
import PageHeader from "@/components/app/PageHeader"
import PageShell from "@/components/app/PageShell"
import LeaveRequestForm from "@/features/leave/components/LeaveRequestForm"

import { listBranches } from "@/features/employees/service"
import { listPublicHolidays } from "@/features/leave/service"
import { db } from "@/lib/db"
import type { PrismaClient } from "@prisma/client"

const prisma = db as PrismaClient as unknown as any

export const dynamic = "force-dynamic"

export default async function CreateLeaveRequestPage() {
  const [branches, publicHolidays, leaveTypes, employees] = await Promise.all([
    listBranches(),
    listPublicHolidays(),
    prisma.leaveType.findMany({ orderBy: { name: "asc" }, select: { id: true, name: true } }),
    prisma.employee.findMany({
      orderBy: { fullName: "asc" },
      select: {
        id: true,
        fullName: true,
        branchId: true,
        departmentId: true,
        subDepartmentId: true,
      },
    }),
  ])

  const employeeOptions = employees.map((e: any) => ({
    id: e.id,
    name: e.fullName,
    branchId: e.branchId ?? undefined,
    departmentId: e.departmentId ?? undefined,
    subDepartmentId: e.subDepartmentId ?? undefined,
  }))

  const leaveTypeOptions = leaveTypes.map((t: any) => ({ id: t.id, name: t.name }))
  const branchOptions = branches.map((b: any) => ({ id: b.id, name: b.name }))

  const holidayOptions = publicHolidays.map((h: any) => ({
    date: h.date instanceof Date ? h.date.toISOString() : h.date,
    endDate: h.endDate instanceof Date ? h.endDate.toISOString() : (h.endDate ?? null),
  }))

  return (
    <PageShell>
      <PageHeader
        title="Add Leave Request"
        description="Create a new leave application for an employee."
        actions={
          <Button asChild variant="secondary">
            <Link href="/leave">Back</Link>
          </Button>
        }
      />
      <LeaveRequestForm
        employees={employeeOptions}
        leaveTypes={leaveTypeOptions}
        branches={branchOptions}
        publicHolidays={holidayOptions}
      />
    </PageShell>
  )
}