import { notFound } from "next/navigation"

import FormShell from "@/components/app/FormShell"
import PageHeader from "@/components/app/PageHeader"
import PageShell from "@/components/app/PageShell"
import { Button } from "@/components/ui/button"
import PayrollForm from "@/features/payroll/components/PayrollForm"
import { getPayrollById, listEmployeesForPayroll } from "@/features/payroll/service"
import { getCountryConfig } from "@/lib/shared/country"
import { listBranches } from "@/features/employees/service"

interface EditPayrollPageProps {
  params: Promise<{ id: string }>
}

export default async function EditPayrollPage({ params }: EditPayrollPageProps) {
  const { id } = await params

  const [payroll, employees, countryConfig, branches] = await Promise.all([
    getPayrollById(id),
    listEmployeesForPayroll(),
    getCountryConfig(),
    listBranches(),
  ])

  if (!payroll) {
    notFound()
  }

  const initialData = {
    id: payroll.id,
    employeeId: payroll.employeeId,
    month: payroll.month,
    year: payroll.year,
    workingDays: payroll.workingDays,
    daysWorked: payroll.daysWorked,
    basicSalary: payroll.basicSalary,
    items: payroll.items.map((i) => ({
      id: i.id,
      type: i.type,
      description: i.description,
      amount: i.amount,
    })),
    notes: payroll.notes || undefined,
    status: payroll.status,
  }

  return (
    <PageShell>
      <PageHeader
        title="Edit Payroll"
        actions={
          <Button asChild variant="secondary">
            <a href="/payroll">Back</a>
          </Button>
        }
      />
      <FormShell>
        <PayrollForm
          branches={branches}
          initialData={initialData}
          employees={employees}
          currencyCode={countryConfig.currencyCode}
          decimalPlaces={countryConfig.decimalPlaces}
        />
      </FormShell>
    </PageShell>
  )
}
