import { Resend } from "resend";
import { render } from "@react-email/components";
import { OrderConfirmation, OrderShipped, OrderCancelled } from "@/emails";

const resend = new Resend(process.env.RESEND_API_KEY);

const FROM_EMAIL = process.env.FROM_EMAIL || "support@mail.manoonoils.com";
const FROM_NAME = process.env.FROM_NAME || "ManoonOils";

export async function sendEmail({
  to,
  subject,
  html,
}: {
  to: string | string[];
  subject: string;
  html: string;
}) {
  const { data, error } = await resend.emails.send({
    from: `${FROM_NAME} <${FROM_EMAIL}>`,
    to,
    subject,
    html,
  });

  if (error) {
    console.error("Resend error:", error);
    throw error;
  }

  return data;
}

export function formatPrice(amount: number, currency: string) {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency,
  }).format(amount);
}

export async function sendOrderConfirmationEmail({
  to,
  orderData,
  isAdmin = false,
}: {
  to: string | string[];
  orderData: {
    orderId: string;
    orderNumber: string;
    customerEmail: string;
    customerName: string;
    items: Array<{ id: string; name: string; quantity: number; price: string }>;
    total: string;
    shippingAddress?: string;
    billingAddress?: string;
    phone?: string;
  };
  isAdmin?: boolean;
}) {
  const html = await render(
    OrderConfirmation({
      ...orderData,
      siteUrl: process.env.SITE_URL || "https://dev.manoonoils.com",
      dashboardUrl: process.env.DASHBOARD_URL || "https://dashboard.manoonoils.com",
      isAdmin,
    })
  );

  const subject = isAdmin
    ? `🎉 New Order #${orderData.orderNumber}`
    : `Order Confirmation #${orderData.orderNumber}`;

  return sendEmail({ to, subject, html });
}

export async function sendOrderShippedEmail({
  to,
  orderData,
}: {
  to: string | string[];
  orderData: {
    orderId: string;
    orderNumber: string;
    customerName: string;
    items: Array<{ id: string; name: string; quantity: number; price: string }>;
    trackingNumber?: string;
    trackingUrl?: string;
  };
}) {
  const html = await render(
    OrderShipped({
      ...orderData,
      siteUrl: process.env.SITE_URL || "https://dev.manoonoils.com",
    })
  );

  return sendEmail({
    to,
    subject: `Your Order #${orderData.orderNumber} Has Shipped!`,
    html,
  });
}

export async function sendOrderCancelledEmail({
  to,
  orderData,
}: {
  to: string | string[];
  orderData: {
    orderId: string;
    orderNumber: string;
    customerName: string;
    items: Array<{ id: string; name: string; quantity: number; price: string }>;
    total: string;
    reason?: string;
  };
}) {
  const html = await render(
    OrderCancelled({
      ...orderData,
      siteUrl: process.env.SITE_URL || "https://dev.manoonoils.com",
    })
  );

  return sendEmail({
    to,
    subject: `Your Order #${orderData.orderNumber} Has Been Cancelled`,
    html,
  });
}
