import DashboardLayout from "@/components/layout/dashboard-layout";
import EmployeeTable from "@/components/admin/employee-table";
import { verifySession } from "@/lib/auth";
import MonthYearPicker from "@/components/admin/month-year-picker";
import { format, getMonth, getYear } from "date-fns";
import { getTranslations, getCurrentLocale } from "@/lib/i18n";
import { getMonthlyDeductions, getMonthlyBonuses } from "@/lib/data-helpers";
import { getCurrencySymbolAsync } from "@/lib/server-currency";
import { getChartOfAccountsWithSeedMerge } from "@/lib/accounting/chart-of-accounts-runtime";
import { getEmployeePermissionProfilesFromSettings, hasEmployeePermission } from "@/lib/employee-permissions";
import type { Employee, Warehouse, ChartOfAccount, JournalEntry } from "@/lib/types";

export const revalidate = 0;

export default async function AdminEmployeesPage({
  searchParams,
}: {
  searchParams?: Promise<{ month?: string; year?: string }>;
}) {
  const session = await verifySession();
  const user = session.user;

  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tGlobal = t.Global;
  const tEmployeeTable = t.EmployeeTable;
  const tDashboardLayout = t.DashboardLayout;

  const today = new Date();
  const params = await searchParams;
  const year = params?.year ? parseInt(params.year) : today.getFullYear();
  const month = params?.month ? parseInt(params.month) - 1 : today.getMonth();
  const selectedDate = new Date(year, month);
  
  let allEmployees: Employee[] = [];
  let warehouses: Warehouse[] = [];
  let chartAccounts: ChartOfAccount[] = [];
  let journalEntries: JournalEntry[] = [];
  let settings: Record<string, any> = {};

  
  const { pgGetEmployees, pgGetActiveWarehouses, pgGetJournalEntries, pgGetSettings } = await import('@/lib/postgres/data-access');
  const [empResult, warehouseResult, journalEntriesResult, settingsResult] = await Promise.all([
  pgGetEmployees({ page: 1, pageSize: 5000 }),
  pgGetActiveWarehouses(),
  pgGetJournalEntries({ page: 1, pageSize: 10000 }),
  pgGetSettings(),
  ]);
  allEmployees = (empResult.items || []) as Employee[];
  warehouses = (warehouseResult.items || []) as Warehouse[];
  journalEntries = (journalEntriesResult.items || []) as JournalEntry[];
  settings = settingsResult || {};
  

  if (!user || !hasEmployeePermission(user, settings, 'admin.employees')) {
    return (
        <DashboardLayout>
            <div className="text-center">
                <h1 className="text-2xl font-bold">{tGlobal.accessDenied}</h1>
                <p>{tGlobal.noPermission}</p>
            </div>
        </DashboardLayout>
    );
  }

  chartAccounts = (await getChartOfAccountsWithSeedMerge()) as ChartOfAccount[];
  const permissionProfiles = getEmployeePermissionProfilesFromSettings(settings);

  const employeesWithStats = allEmployees.map(employee => {
    const { total: totalDeductions, records: deductionRecords } = getMonthlyDeductions(employee, month, year);
    const { total: totalBonuses, records: bonusRecords } = getMonthlyBonuses(employee, month, year);
    const attendedDays = employee.attendance.filter(att => {
        const attDate = new Date(att.checkIn);
        return getYear(attDate) === year && getMonth(attDate) === month && att.checkOut !== null;
    }).length;
    return {
        ...employee,
        totalDeductions,
        deductionRecords,
        totalBonuses,
        bonusRecords,
        attendedDays
    };
  });

  const currencySymbol = await getCurrencySymbolAsync();

  return (
    <DashboardLayout>
      <div className="w-full max-w-7xl mx-auto">
        <div className="flex justify-between items-center mb-4">
          <h1 className="text-2xl font-bold">{tDashboardLayout.employees}</h1>
          <MonthYearPicker initialDate={selectedDate} basePath="/admin/employees" />
        </div>
        <div>
          <EmployeeTable employees={employeesWithStats} month={month} year={year} t={tEmployeeTable} currencySymbol={currencySymbol} warehouses={warehouses} chartAccounts={chartAccounts} permissionProfiles={permissionProfiles} journalEntries={journalEntries} />
        </div>
      </div>
    </DashboardLayout>
  );
}
