import { notFound } from 'next/navigation';
import { verifySession } from '@/lib/auth';
import { pgGetWarehouses, pgGetEmployees, pgGetManagedUnits } from '@/lib/postgres/data-access';
import { getTranslations, getCurrentLocale } from '@/lib/i18n';
import WarehouseEditForm from '@/components/admin/warehouse-edit-form';
import type { Warehouse } from '@/lib/types';

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

  if (!user || user.role !== 'admin') {
    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 warehouse = warehouses.find((w) => w.id === params.id);
  if (!warehouse) notFound();

  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((w) => {
    const branch = String((w as any)?.branchName || '').trim();
    if (branch) branchSet.add(branch);
  });
  if (branchSet.size === 0) branchSet.add('الفرع الرئيسي');

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