"use client";

import {
  type WholesaleOrder,
  type WholesaleCustomer,
  enqueueWholesaleNotification,
  getWholesaleSettings,
  markWholesaleOrderFulfilled,
} from "@/actions/wholesale";

export async function fulfillWithNotifications(
  orderId: string,
  orders: WholesaleOrder[],
  customers: WholesaleCustomer[],
  brandId: string,
): Promise<{ success: boolean; error?: string }> {
  const result = await markWholesaleOrderFulfilled(orderId);
  if (!result.success) return result;

  const order = orders.find(o => o.id === orderId);
  const customer = order ? customers.find(c => c.email === order.customer_email) : null;
  if (order && customer) {
    enqueueWholesaleNotification({
      brandId: brandId,
      customerId: customer.id,
      orderId,
      type: "order_fulfilled",
      emailTo: customer.email,
      subject: `Order ${order.invoice_number ?? orderId.slice(0, 8)} Ready for Pickup`,
      bodyHtml: `
        <h2>Your Order is Ready!</h2>
        <p>Hi ${customer.company_name},</p>
        <p>Your wholesale order <strong>${order.invoice_number ?? orderId.slice(0, 8)}</strong> has been fulfilled and is ready for pickup${order.anticipated_pickup_date ? ` on ${order.anticipated_pickup_date}` : ""}.</p>
        <p>Thank you for your business!</p>
      `,
      bodyText: `Order ${order.invoice_number ?? orderId.slice(0, 8)} has been fulfilled and is ready for pickup${order.anticipated_pickup_date ? ` on ${order.anticipated_pickup_date}` : ""}. Thank you!`,
    });

    const settings = await getWholesaleSettings(brandId);
    const adminEmail = settings?.notification_email ?? settings?.from_email ?? settings?.invoice_business_email ?? null;
    if (adminEmail) {
      enqueueWholesaleNotification({
        brandId: brandId,
        customerId: customer.id,
        orderId,
        type: "order_fulfilled",
        emailTo: adminEmail,
        subject: `[Admin] Order Fulfilled — ${order.invoice_number ?? orderId.slice(0, 8)}`,
        bodyHtml: `
          <h2>Order Fulfilled</h2>
          <p>Order <strong>${order.invoice_number ?? orderId.slice(0, 8)}</strong> for <strong>${customer.company_name}</strong> has been marked as fulfilled.</p>
          ${order.anticipated_pickup_date ? `<p><strong>Pickup Date:</strong> ${order.anticipated_pickup_date}</p>` : ""}
        `,
        bodyText: `Order ${order.invoice_number ?? orderId.slice(0, 8)} for ${customer.company_name} has been fulfilled.`,
      });
    }

    fetch(`/api/wholesale/notifications/send`, { method: "POST" }).catch(() => {});
  }
  return { success: true };
}

function generateManifestHtml(orders: WholesaleOrder[], brandId: string): Promise<string> {
  return fetch("/api/wholesale/manifest", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ brandId, orders }),
  }).then(r => r.text());
}

export function openManifestWindow(orders: WholesaleOrder[], brandId: string): void {
  generateManifestHtml(orders, brandId).then(html => {
    const blob = new Blob([html], { type: "text/html;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const w = window.open(url, "_blank");
    if (w) {
      w.addEventListener("load", () => URL.revokeObjectURL(url), { once: true });
      setTimeout(() => URL.revokeObjectURL(url), 60_000);
    } else {
      URL.revokeObjectURL(url);
    }
  });
}
