import { verifySession } from '@/lib/auth';
import { pgGetManagedUnits, pgGetWarehouses, pgGetEmployees } from '@/lib/postgres/data-access';
import { hasEmployeePermission } from '@/lib/employee-permissions';
import { getTranslations, getCurrentLocale } from '@/lib/i18n';
import WarehouseShelfManager from '@/components/admin/warehouse-shelf-manager';
import type { Warehouse } from '@/lib/types';

export default async function ManageWarehousesPage() {
  const session = await verifySession();
  const user = session.user;
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tGlobal = t.Global || {};
  const tLists = t.ItemLists || {};

  const settings = await (await import('@/lib/postgres/data-access')).pgGetSettings();
  if (!user || !hasEmployeePermission(user, settings, 'admin.materials')) {
    return (
      <div className="text-center">
        <h1 className="text-2xl font-bold">{tGlobal?.accessDenied ?? 'Access denied'}</h1>
        <p>{tGlobal?.noPermission ?? 'You do not have permission to view this page.'}</p>
      </div>
    );
  }

  const warehouses: Warehouse[] = (await pgGetWarehouses({ page: 1, pageSize: 5000 })).items as Warehouse[];

  const employees: Array<{ id: string; name: string }> = ((await pgGetEmployees({ page: 1, pageSize: 10000 })).items || [])
    .map((entry: any) => ({ id: String(entry?.id || ''), name: String(entry?.name || '') }))
    .filter((entry: { id: string; name: string }) => entry.id && entry.name);

  const managedUnits = ((await pgGetManagedUnits({ page: 1, pageSize: 5000 })).items || []);
  const branchSet = new Set<string>();
  managedUnits.forEach((unit: any) => {
    const description = String(unit?.description || '').trim();
    if (description) branchSet.add(description);
  });
  warehouses.forEach((warehouse) => {
    const branch = String((warehouse as any)?.branchName || '').trim();
    if (branch) branchSet.add(branch);
  });
  if (branchSet.size === 0) {
    branchSet.add('الفرع الرئيسي');
  }

  return (
    <div className="w-full max-w-6xl mx-auto">
      <WarehouseShelfManager
        warehouses={warehouses}
        employees={employees}
        branchOptions={Array.from(branchSet).sort((a, b) => a.localeCompare(b))}
        t={tLists}
        tGlobal={tGlobal}
      />
    </div>
  );
}
