import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { getAdminUser } from "@/lib/admin-permissions";
import { pool } from "@/lib/db";
import {
  getWholesaleCustomer,
  getWholesaleCustomerByUser,
  getWholesaleProducts,
  getWholesaleCustomerOrders,
  getWholesaleCustomerPricing,
  type WholesaleProduct,
  type WholesaleCustomerOrder,
} from "@/actions/wholesale-register";
import WholesalePortalClient, { type WholesaleCustomer } from "./WholesalePortalClient";

type SearchParams = Promise<{
  _admin_preview?: string;
  preview_customer_id?: string;
}>;

export const dynamic = "force-dynamic";

type WholesaleSettingsRow = {
  wholesale_enabled: boolean | null;
  online_payment_enabled: boolean | null;
};

export default async function WholesalePortalPage({
  searchParams,
}: {
  searchParams: SearchParams;
}) {
  const params = await searchParams;
  const isPreview = params._admin_preview === "1";
  const previewCustomerId = params.preview_customer_id;

  const [adminUser, cookieStore] = await Promise.all([
    getAdminUser(),
    cookies(),
  ]);
  const sessionCookie = cookieStore.get("wholesale_session")?.value;

  let customer: WholesaleCustomer | null = null;
  let brandName = "Wholesale Portal";
  let products: WholesaleProduct[] = [];
  let orders: WholesaleCustomerOrder[] = [];
  let pricingOverrides: Record<string, number> = {};
  let onlinePaymentEnabled = false;
  let previewMode = false;
  let invalidPreview = false;

  if (isPreview && previewCustomerId) {
    // ── Admin preview mode (requires admin auth) ──────────────────────────
    if (!adminUser) redirect("/admin/login?next=/wholesale/portal");
    const cust = await getWholesaleCustomer(previewCustomerId);
    if (!cust) {
      invalidPreview = true;
    } else {
      customer = cust;
      previewMode = true;
      const [brandRow, prodList, orderList, pricingList, wsRow] = await Promise.all([
        pool.query<{ name: string }>("SELECT name FROM brands WHERE id = $1 LIMIT 1", [cust.brand_id]),
        getWholesaleProducts(cust.brand_id),
        getWholesaleCustomerOrders(cust.id),
        getWholesaleCustomerPricing(cust.id),
        pool.query<WholesaleSettingsRow>(
          "SELECT wholesale_enabled, online_payment_enabled FROM wholesale_settings WHERE brand_id = $1 LIMIT 1",
          [cust.brand_id],
        ),
      ]);
      brandName = brandRow.rows[0]?.name ?? "Wholesale Portal";
      products = prodList as WholesaleProduct[];
      orders = orderList as WholesaleCustomerOrder[];
      const pricingMap: Record<string, number> = {};
      for (const p of pricingList) {
        pricingMap[p.product_id] = p.custom_unit_price;
      }
      pricingOverrides = pricingMap;
      onlinePaymentEnabled = wsRow.rows[0]?.online_payment_enabled ?? false;
    }
  } else if (sessionCookie) {
    // ── Session-based login (legacy path; wholesale login is currently stubbed) ──
    if (!adminUser) redirect("/wholesale/login");
    let userId: string;
    let parsedSession: { user_id?: string } | null = null;
    try {
      parsedSession = JSON.parse(sessionCookie) as { user_id?: string };
    } catch {
      parsedSession = null;
    }
    if (!parsedSession?.user_id) {
      redirect("/wholesale/login");
    }
    userId = parsedSession.user_id;
    const cust = await getWholesaleCustomerByUser(
      "00000000-0000-0000-0000-000000000000",
      userId,
    );
    if (!cust || cust.account_status !== "active") {
      redirect("/wholesale/login?error=account_not_active");
    }
    customer = cust;
    const [brandRow, prodList, orderList, pricingList, wsRow] = await Promise.all([
      pool.query<{ name: string }>("SELECT name FROM brands WHERE id = $1 LIMIT 1", [cust.brand_id]),
      getWholesaleProducts(cust.brand_id),
      getWholesaleCustomerOrders(cust.id),
      getWholesaleCustomerPricing(cust.id),
      pool.query<WholesaleSettingsRow>(
        "SELECT wholesale_enabled, online_payment_enabled FROM wholesale_settings WHERE brand_id = $1 LIMIT 1",
        [cust.brand_id],
      ),
    ]);
    if (wsRow.rows[0]?.wholesale_enabled === false) {
      redirect("/wholesale/login?error=portal_disabled");
    }
    brandName = brandRow.rows[0]?.name ?? "Wholesale Portal";
    products = prodList as WholesaleProduct[];
    orders = orderList as WholesaleCustomerOrder[];
    const pricingMap: Record<string, number> = {};
    for (const p of pricingList) {
      pricingMap[p.product_id] = p.custom_unit_price;
    }
    pricingOverrides = pricingMap;
    onlinePaymentEnabled = wsRow.rows[0]?.online_payment_enabled ?? false;
  } else {
    // ── No auth — redirect to login ───────────────────────────────────────
    redirect("/wholesale/login");
  }

  return (
    <WholesalePortalClient
      customer={customer}
      brandName={brandName}
      products={products}
      orders={orders}
      pricingOverrides={pricingOverrides}
      onlinePaymentEnabled={onlinePaymentEnabled}
      previewMode={previewMode}
      invalidPreview={invalidPreview}
    />
  );
}