import LeaveRequestsTable from '@/components/admin/leave-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 AdminLeaveRequestsPage() {
    const session = await verifySession();

    const locale = await getCurrentLocale();
    const t = getTranslations(locale);
    const tGlobal = t.Global;
    const tLeaveRequests = t.LeaveRequests;
    
    const settings = await (await import('@/lib/postgres/data-access')).pgGetSettings();
    if (!session.user || !hasEmployeePermission(session.user, settings, 'admin.leave-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 allLeaveRequests = 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>{tLeaveRequests.title}</CardTitle>
                        <CardDescription>{tLeaveRequests.description}</CardDescription>
                    </CardHeader>
                    <CardContent>
                        <LeaveRequestsTable requests={allLeaveRequests} t={tLeaveRequests} />
                    </CardContent>
                </Card>
            </div>
        </DashboardLayout>
    );
}
