import DashboardLayout from "@/components/layout/dashboard-layout";
import { notFound } from "next/navigation";
import FinancialsForm from "@/components/admin/financials-form";
import FinancialRecordsList from "@/components/admin/financial-records-list";
import { getTranslations, getCurrentLocale } from "@/lib/i18n";
import { type Employee, type LeaveRequest } from "@/lib/types";

export default async function FinancialsPage({ 
    params
}: { 
    params: Promise<{ id: string }>,
}) {
    const { id } = await params;
    const employee = (((await (await import('@/lib/postgres/data-access')).pgGetEmployees({ page: 1, pageSize: 5000 })).items || []) as Employee[]).find((entry) => entry.id === id) as Employee | undefined;

    if (!employee) {
        notFound();
    }
    
    const locale = await getCurrentLocale();
    const t = getTranslations(locale);
    const tFinancials = t.Financials;
    const tGlobal = t.Global;

    // Find approved advance requests that haven't been scheduled yet
    const scheduledRequestIds = new Set(employee.financialRecords.map(fr => fr.requestId).filter(Boolean));
    const unscheduledApprovedRequests = employee.leaveRequests.filter(
        req => req.requestType === 'advance' && req.status === 'approved' && !scheduledRequestIds.has(req.id)
    );

    return (
        <DashboardLayout>
            <div className="mx-auto grid w-full max-w-6xl gap-2">
                <h1 className="text-3xl font-semibold">{tFinancials.title.replace('{employeeName}', employee.name)}</h1>
                <p className="text-muted-foreground">
                    {tFinancials.description}
                </p>
            </div>
            <div className="mx-auto w-full max-w-6xl mt-8 space-y-8">
               <FinancialsForm 
                    employee={employee} 
                    t={tFinancials} 
                    tGlobal={tGlobal} 
                    unscheduledApprovedRequests={unscheduledApprovedRequests as Omit<LeaveRequest, 'employeeId' | 'employeeName' | 'toEmployeeName'>[]}
                />
               <FinancialRecordsList employee={employee} t={tFinancials} tGlobal={tGlobal} />
            </div>
        </DashboardLayout>
    )
}
