import AdvanceRequestsTable from '@/components/admin/advance-requests-table';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import DashboardLayout from '@/components/layout/dashboard-layout';
import { verifySession } from '@/lib/auth';
import { hasEmployeePermission } from '@/lib/employee-permissions';
import { getTranslations, getCurrentLocale } from '@/lib/i18n';

export default async function AdminAdvanceRequestsPage() {
    const session = await verifySession();

    const locale = await getCurrentLocale();
    const t = getTranslations(locale);
    const tGlobal = t.Global;
    const tAdvanceRequests = t.AdvanceRequests;
    
    const settings = await (await import('@/lib/postgres/data-access')).pgGetSettings();
    if (!session.user || !hasEmployeePermission(session.user, settings, 'admin.advance-requests')) {
        return (
            <DashboardLayout>
                <div className="text-center">
                    <h1 className="text-2xl font-bold">{tGlobal.accessDenied}</h1>
                    <p>{tGlobal.noPermission}</p>
                </div>
            </DashboardLayout>
        );
    }
    
    const employees = (await (await import('@/lib/postgres/data-access')).pgGetEmployees({ page: 1, pageSize: 5000 })).items as any[];

    const advanceRequests = employees
        .flatMap((employee) =>
            (employee.leaveRequests || []).map((request: any) => ({
                ...request,
                employeeId: employee.id,
                employeeName: employee.name,
            }))
        )
        .filter((req) => req.requestType === 'advance');

    return (
        <DashboardLayout>
            <div className="w-full max-w-7xl mx-auto">
                <Card>
                    <CardHeader>
                        <CardTitle>{tAdvanceRequests.title}</CardTitle>
                        <CardDescription>{tAdvanceRequests.description}</CardDescription>
                    </CardHeader>
                    <CardContent>
                        <AdvanceRequestsTable requests={advanceRequests} t={tAdvanceRequests} tGlobal={tGlobal} />
                    </CardContent>
                </Card>
            </div>
        </DashboardLayout>
    );
}
