import DashboardLayout from '@/components/layout/dashboard-layout';
import { pgGetActiveWarehouses, pgGetInvoices, pgGetMaterialStockLocations } from '@/lib/postgres/data-access';
import StoreOrdersClient from '@/components/admin/store/store-orders-client';
import { verifySession } from '@/lib/auth';
import { redirect } from 'next/navigation';

export const dynamic = 'force-dynamic';

export default async function StoreOrdersPage() {
  const { user } = await verifySession();
  if (!user || (user.role !== 'admin' && user.role !== 'pos')) {
    redirect('/login');
  }

  // Fetch all invoices and filter store ones
  const [result, warehousesResult] = await Promise.all([
    pgGetInvoices({ page: 1, pageSize: 5000 }),
    pgGetActiveWarehouses(),
  ]);
  const allInvoices = (result.items || []) as any[];
  const warehouses = (warehousesResult?.items || []) as any[];
  const storeOrders = allInvoices.filter(
    (inv) => inv.source === 'store' || String(inv.invoiceNumber || '').startsWith('STORE/')
  );
  const materialIds = Array.from(
    new Set(
      storeOrders.flatMap((order) =>
        (Array.isArray(order.items) ? order.items : [])
          .map((item: any) => String(item?.materialId || '').trim())
          .filter(Boolean)
      )
    )
  );
  const stockLocations = materialIds.length > 0 ? await pgGetMaterialStockLocations(materialIds) : {};

  // Sort newest first
  storeOrders.sort((a, b) =>
    new Date(b.createdAt || b.date || 0).getTime() - new Date(a.createdAt || a.date || 0).getTime()
  );

  return (
    <DashboardLayout>
      <div className="mx-auto w-full max-w-7xl space-y-4 px-4 py-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold">إدارة طلبات المتجر</h1>
            <p className="text-sm text-muted-foreground mt-1">
              الطلبات الواردة من المتجر الإلكتروني — إجمالي {storeOrders.length} طلب
            </p>
          </div>
        </div>
        <StoreOrdersClient orders={storeOrders} warehouses={warehouses} stockLocations={stockLocations} />
      </div>
    </DashboardLayout>
  );
}
