import { Resend } from "resend"

const FROM = process.env.EMAIL_FROM || "Axis Print Management <noreply@axismaxlife.com>"

function getResend() {
  if (!process.env.RESEND_API_KEY) {
    console.error("[EMAIL ERROR] RESEND_API_KEY is not set")
    return null
  }
  return new Resend(process.env.RESEND_API_KEY)
}

function baseTemplate(title: string, body: string) {
  return `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
<body style="margin:0;padding:0;background:#f1f5f9;font-family:Arial,sans-serif">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#f1f5f9;padding:40px 0">
    <tr><td align="center">
      <table width="600" cellpadding="0" cellspacing="0" style="background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.08)">
        <tr><td style="background:#003c71;padding:24px 32px">
          <h1 style="margin:0;color:#fff;font-size:20px;font-weight:700">Axis Max Life</h1>
          <p style="margin:4px 0 0;color:#93c5fd;font-size:13px">Print Management System</p>
        </td></tr>
        <tr><td style="padding:32px">
          <h2 style="margin:0 0 16px;color:#0f172a;font-size:18px">${title}</h2>
          ${body}
          <hr style="border:none;border-top:1px solid #e2e8f0;margin:32px 0">
          <p style="margin:0;color:#94a3b8;font-size:12px">This is an automated message from Axis Max Life Print Management System. Please do not reply to this email.</p>
        </td></tr>
      </table>
    </td></tr>
  </table>
</body>
</html>`
}

function infoRow(label: string, value: string) {
  return `<tr>
    <td style="padding:8px 12px;color:#64748b;font-size:13px;width:140px">${label}</td>
    <td style="padding:8px 12px;color:#0f172a;font-size:13px;font-weight:600">${value}</td>
  </tr>`
}

function button(text: string, url: string, color = "#003c71") {
  return `<a href="${url}" style="display:inline-block;background:${color};color:#fff;padding:12px 24px;border-radius:8px;text-decoration:none;font-weight:600;font-size:14px;margin-top:16px">${text}</a>`
}

export async function sendProjectApprovedEmail(to: string, data: {
  pocName: string; projectName: string; projectId: string; location: string; totalCost: string; appUrl: string
}) {
  const resend = getResend()
  if (!resend) {
    console.error("[EMAIL ERROR] Cannot send approval email - Resend not initialized")
    return
  }
  try {
    const result = await resend.emails.send({
      from: FROM, to,
      subject: `System Notification: Project Approved – ${data.projectName} | Status Update`,
      html: baseTemplate("Project Approved", `
        <p style="color:#475569;margin:0 0 20px">Dear ${data.pocName},</p>
        <p style="color:#475569;margin:0 0 20px">This is an automated system notification generated by Rishiraj Media.</p>
        <p style="color:#475569;margin:0 0 20px">Please be informed that your project request has been reviewed and approved. The project will now proceed to the next stage of execution as per the defined workflow.</p>
        <p style="color:#003c71;margin:0 0 12px;font-weight:600">Project Details:</p>
        <table style="background:#f8fafc;border-radius:8px;width:100%;border-collapse:collapse;margin-bottom:20px">
          ${infoRow("Project ID", data.projectId)}
          ${infoRow("Project Name", data.projectName)}
          ${infoRow("Location", data.location)}
          ${infoRow("Total Cost", data.totalCost)}
        </table>
        <p style="color:#475569;margin:0 0 20px">You will be notified upon completion of subsequent stages or in case of any exceptions requiring your attention.</p>
        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0">
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Please Note:</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px">This is a system-generated communication issued by Rishiraj Media for status tracking and audit purposes. The information contained herein is confidential and intended solely for the designated recipient.</p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>No action is required at this stage.</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0">Do not reply directly to this email.</p>
      `),
    })
    console.log(`[EMAIL SENT] Project approved email sent to ${to}`, result)
  } catch (error) {
    console.error(`[EMAIL ERROR] Failed to send approval email to ${to}:`, error)
  }
}

export async function sendProjectRejectedEmail(to: string, data: {
  pocName: string; projectName: string; projectId: string; reason?: string; appUrl: string
}) {
  const resend = getResend()
  if (!resend) return
  try {
    await resend.emails.send({
      from: FROM, to,
      subject: `System Notification: Project Rejected – ${data.projectName} | Attention Required`,
      html: baseTemplate("Project Rejected", `
        <p style="color:#475569;margin:0 0 20px">Dear ${data.pocName},</p>
        <p style="color:#475569;margin:0 0 20px">This is an automated system notification generated by Rishiraj Media.</p>
        <p style="color:#475569;margin:0 0 20px">Please be informed that your project request has been reviewed and rejected. The project cannot proceed to the next stage as submitted.</p>
        <p style="color:#003c71;margin:0 0 12px;font-weight:600">Project Details:</p>
        <table style="background:#f8fafc;border-radius:8px;width:100%;border-collapse:collapse;margin-bottom:20px">
          ${infoRow("Project ID", data.projectId)}
          ${infoRow("Project Name", data.projectName)}
          ${data.reason ? infoRow("Reason for Rejection", data.reason) : ""}
        </table>
        <p style="color:#475569;margin:0 0 20px">Please review the reason for rejection and submit a revised request or contact your designated account representative for further clarification.</p>
        <p style="color:#475569;margin:0 0 20px">For any clarifications or assistance, kindly coordinate with your designated account representative or respond via the appropriate communication channel.</p>
        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0">
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Please Note:</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px">This is a system-generated communication issued by Rishiraj Media for process compliance and audit tracking. The information contained herein is confidential and intended solely for the designated recipient.</p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Action Required:</strong> Submit revised request or contact account representative</p>
        <p style="color:#64748b;font-size:12px;margin:0">Do not reply directly to this email.</p>
      `),
    })
    console.log(`[EMAIL SENT] Project rejected email sent to ${to}`)
  } catch (error) {
    console.error(`[EMAIL ERROR] Failed to send project rejected email to ${to}`, error)
  }
}

export async function sendDispatchNotificationEmail(to: string, data: {
  pocName: string; projectName: string; projectId: string; courier: string
  trackingId: string; expectedDelivery: string; appUrl: string
}) {
  const resend = getResend()
  if (!resend) return
  try {
    await resend.emails.send({
      from: FROM, to,
      subject: `System Notification: Material Dispatched – ${data.projectName} | Shipment Details`,
      html: baseTemplate("Material Dispatched", `
        <p style="color:#475569;margin:0 0 20px">Dear ${data.pocName},</p>
        <p style="color:#475569;margin:0 0 20px">This is an automated system notification generated by Rishiraj Media.</p>
        <p style="color:#475569;margin:0 0 20px">Please be informed that the materials associated with the project referenced below have been dispatched from the production facility.</p>
        <p style="color:#003c71;margin:0 0 12px;font-weight:600">Shipment Details:</p>
        <table style="background:#f8fafc;border-radius:8px;width:100%;border-collapse:collapse;margin-bottom:20px">
          ${infoRow("Project ID", data.projectId)}
          ${infoRow("Project Name", data.projectName)}
          ${infoRow("Courier / Transport Partner", data.courier)}
          ${infoRow("Tracking ID", data.trackingId)}
          ${infoRow("Expected Delivery", data.expectedDelivery)}
        </table>
        <p style="color:#475569;margin:0 0 20px">The shipment is currently in transit. You may track the status through Mailroom.</p>
        ${button("Track Shipment", `${data.appUrl}/projects`)}
        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0">
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Please Note:</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px">This is a system-generated communication issued by Rishiraj Media for operational tracking and audit purposes. The information contained herein is confidential and intended solely for the designated recipient.</p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Action Required:</strong> Please monitor shipment and arrange for receipt.</p>
        <p style="color:#64748b;font-size:12px;margin:0">Do not reply directly to this email.</p>
      `),
    })
    console.log(`[EMAIL SENT] Dispatch notification email sent to ${to}`)
  } catch (error) {
    console.error(`[EMAIL ERROR] Failed to send dispatch notification email to ${to}`, error)
  }
}

export async function sendApprovalReminderEmail(to: string, data: {
  adminName: string; projectName: string; projectId: string
  pocName: string; totalCost: string; reminderCount: number; appUrl: string
}) {
  const resend = getResend()
  if (!resend) return
  try {
    await resend.emails.send({
      from: FROM, to,
      subject: `Reminder: Pending Approval – ${data.projectName} | Action Required`,
      html: baseTemplate("Pending Approval Reminder", `
        <p style="color:#475569;margin:0 0 20px">Dear ${data.adminName},</p>
        <p style="color:#475569;margin:0 0 20px">This is an automated reminder generated by Rishiraj Media.</p>
        <p style="color:#475569;margin:0 0 20px">This is a reminder #${data.reminderCount} that the following project is awaiting your approval.</p>
        <p style="color:#003c71;margin:0 0 12px;font-weight:600">Reference Details:</p>
        <table style="background:#f8fafc;border-radius:8px;width:100%;border-collapse:collapse;margin-bottom:20px">
          ${infoRow("Project ID", data.projectId)}
          ${infoRow("Project Name", data.projectName)}
          ${infoRow("Requested By", data.pocName)}
          ${infoRow("Total Cost", data.totalCost)}
        </table>
        <p style="color:#475569;margin:0 0 20px">You are requested to review and approve the project at the earliest to enable further processing and avoid any delays.</p>
        ${button("Review & Approve", `${data.appUrl}/approvals`)}
        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0">
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Please Note:</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px">This is a system-generated reminder issued by Rishiraj Media for process compliance and audit tracking. The information contained herein is confidential and intended solely for the designated recipient.</p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Action Required:</strong> Review and approve project</p>
        <p style="color:#64748b;font-size:12px;margin:0">Do not reply directly to this email.</p>
      `),
    })
    console.log(`[EMAIL SENT] Approval reminder email sent to ${to}`)
  } catch (error) {
    console.error(`[EMAIL ERROR] Failed to send approval reminder email to ${to}`, error)
  }
}

export async function sendPasswordResetEmail(to: string, data: {
  name: string; resetUrl: string
}) {
  const resend = getResend()
  if (!resend) return
  await resend.emails.send({
    from: FROM, to,
    subject: "Reset Your Password — Axis Print Management",
    html: baseTemplate("Reset Your Password", `
      <p style="color:#475569;margin:0 0 20px">Hi ${data.name},</p>
      <p style="color:#475569;margin:0 0 20px">We received a request to reset your password. Click the button below to set a new password. This link expires in <strong>1 hour</strong>.</p>
      ${button("Reset Password", data.resetUrl)}
      <p style="color:#94a3b8;font-size:13px;margin-top:20px">If you didn't request this, you can safely ignore this email. Your password won't change.</p>
    `),
  })
}

// Generic sendEmail for simple text notifications
export async function sendEmail({
  to,
  subject,
  text,
}: {
  to: string
  subject: string
  text: string
}) {
  const resend = getResend()
  if (!resend) return
  await resend.emails.send({
    from: FROM,
    to,
    subject,
    text,
  })
}

// User Management Emails

export async function sendWelcomeEmail(to: string, data: {
  name: string
  email: string
  password: string
  role: string
  appUrl: string
}) {
  const resend = getResend()
  if (!resend) {
    console.error("[EMAIL ERROR] Cannot send welcome email - Resend not initialized")
    return
  }

  const roleDisplay = data.role === "ADMIN" ? "Administrator" : data.role === "POC" ? "Point of Contact (POC)" : "Client"
  const roleDescription = data.role === "ADMIN"
    ? "You have full access to manage projects, approvals, team members, and system settings."
    : data.role === "POC"
      ? "You can create and manage print projects, track orders, and coordinate with the admin team."
      : "You have view-only access to track your print projects and order status."

  try {
    const result = await resend.emails.send({
      from: FROM,
      to,
      subject: `System Notification: Account Created – ${data.name} | Welcome`,
      html: baseTemplate("Account Created Successfully", `
        <p style="color:#475569;margin:0 0 20px">Dear ${data.name},</p>
        <p style="color:#475569;margin:0 0 20px">This is an automated system notification generated by Rishiraj Media.</p>
        <p style="color:#475569;margin:0 0 20px">Your account has been successfully created in the Axis Print Management system. You are now registered as a <strong>${roleDisplay}</strong>.</p>
        <p style="color:#003c71;margin:0 0 12px;font-weight:600">Account Details:</p>
        <table style="background:#f8fafc;border-radius:8px;width:100%;border-collapse:collapse;margin-bottom:20px">
          ${infoRow("Email", data.email)}
          ${infoRow("Temporary Password", `<code style="background:#e2e8f0;padding:4px 8px;border-radius:4px;font-family:monospace">${data.password}</code>`)}
          ${infoRow("Role", roleDisplay)}
        </table>
        <p style="color:#475569;margin:0 0 20px">${roleDescription}</p>
        <p style="color:#dc2626;margin:0 0 20px;font-size:13px"><strong>Important:</strong> Please change your password after your first login for security.</p>
        ${button("Login to Your Account", `${data.appUrl}/login`)}
        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0">
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Please Note:</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px">This is a system-generated communication issued by Rishiraj Media. It is intended solely for the designated recipient.</p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Action Required:</strong> Login and change your password.</p>
        <p style="color:#64748b;font-size:12px;margin:0">Do not reply directly to this email.</p>
      `),
    })
    console.log(`[EMAIL SENT] Welcome email sent to ${to}`, result)
    return result
  } catch (error) {
    console.error(`[EMAIL ERROR] Failed to send welcome email to ${to}:`, error)
    throw error
  }
}

export async function sendRoleChangeEmail(to: string, data: {
  name: string
  oldRole: string
  newRole: string
  appUrl: string
}) {
  const resend = getResend()
  if (!resend) {
    console.error("[EMAIL ERROR] Cannot send role change email - Resend not initialized")
    return
  }

  const oldRoleDisplay = data.oldRole === "ADMIN" ? "Administrator" : data.oldRole === "POC" ? "Point of Contact" : "Client"
  const newRoleDisplay = data.newRole === "ADMIN" ? "Administrator" : data.newRole === "POC" ? "Point of Contact" : "Client"

  try {
    const result = await resend.emails.send({
      from: FROM,
      to,
      subject: `System Notification: Account Role Updated – ${data.name} | Information`,
      html: baseTemplate("Account Role Updated", `
        <p style="color:#475569;margin:0 0 20px">Dear ${data.name},</p>
        <p style="color:#475569;margin:0 0 20px">This is an automated system notification generated by Rishiraj Media.</p>
        <p style="color:#475569;margin:0 0 20px">Please be informed that your account role has been updated in the system.</p>
        <p style="color:#003c71;margin:0 0 12px;font-weight:600">Role Change Details:</p>
        <table style="background:#f8fafc;border-radius:8px;width:100%;border-collapse:collapse;margin-bottom:20px">
          ${infoRow("Previous Role", oldRoleDisplay)}
          ${infoRow("New Role", newRoleDisplay)}
        </table>
        <p style="color:#475569;margin:0 0 20px">Your permissions have been updated accordingly. Please log in again to see the changes.</p>
        ${button("Login to Your Account", `${data.appUrl}/login`)}
        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0">
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Please Note:</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px">This is a system-generated communication issued by Rishiraj Media for process compliance and audit purposes. The information contained herein is confidential and intended solely for the designated recipient.</p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Action Required:</strong> Login again to see permission changes.</p>
        <p style="color:#64748b;font-size:12px;margin:0">Do not reply directly to this email.</p>
      `),
    })
    console.log(`[EMAIL SENT] Role change email sent to ${to}`, result)
  } catch (error) {
    console.error(`[EMAIL ERROR] Failed to send role change email to ${to}:`, error)
  }
}

export async function sendAccountStatusEmail(to: string, data: {
  name: string
  status: "activated" | "deactivated"
  appUrl: string
}) {
  const resend = getResend()
  if (!resend) {
    console.error("[EMAIL ERROR] Cannot send account status email - Resend not initialized")
    return
  }

  const isActive = data.status === "activated"
  const title = isActive ? "Account Activated" : "Account Deactivated"
  const statusLabel = isActive ? "Activated" : "Deactivated"

  try {
    const result = await resend.emails.send({
      from: FROM,
      to,
      subject: `System Notification: Account ${statusLabel} – ${data.name} | ${isActive ? 'Information' : 'Attention Required'}`,
      html: baseTemplate(title, `
        <p style="color:#475569;margin:0 0 20px">Dear ${data.name},</p>
        <p style="color:#475569;margin:0 0 20px">This is an automated system notification generated by Rishiraj Media.</p>
        <p style="color:#475569;margin:0 0 20px">Please be informed that your account has been <strong style="color:${isActive ? '#16a34a' : '#dc2626'}">${statusLabel.toLowerCase()}</strong> in the system.</p>
        ${isActive ? `
        <p style="color:#475569;margin:0 0 20px">You can now log in and access the system using your credentials.</p>
        ${button("Login to Your Account", `${data.appUrl}/login`)}
        ` : `
        <p style="color:#475569;margin:0 0 20px">You will no longer be able to access the system. Please contact your administrator if you believe this was a mistake.</p>
        `}
        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0">
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Please Note:</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px">This is a system-generated communication issued by Rishiraj Media for process compliance and audit purposes. The information contained herein is confidential and intended solely for the designated recipient.</p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>${isActive ? 'Action Required: Login using your credentials' : 'No action required from your end'}</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0">Do not reply directly to this email.</p>
      `),
    })
    console.log(`[EMAIL SENT] Account status email sent to ${to}`, result)
  } catch (error) {
    console.error(`[EMAIL ERROR] Failed to send account status email to ${to}:`, error)
  }
}

// 1. PI Generated Email
export async function sendPIGeneratedEmail(to: string, data: {
  pocName: string; projectName: string; piNumber: string; piDate: string; piAmount: string; appUrl: string
}) {
  const resend = getResend()
  if (!resend) return
  try {
    await resend.emails.send({
      from: FROM, to,
      subject: `Attach: PI | Proforma Invoice Issued – ${data.projectName} | Action Required`,
      html: baseTemplate("Proforma Invoice Issued", `
        <p style="color:#475569;margin:0 0 20px">Dear ${data.pocName},</p>
        <p style="color:#475569;margin:0 0 20px">This is an automated system notification generated by Rishiraj Media.</p>
        <p style="color:#475569;margin:0 0 20px">A Proforma Invoice (PI) has been successfully issued for the project referenced below. The document is attached for your review and necessary action.</p>
        <p style="color:#003c71;margin:0 0 12px;font-weight:600">Transaction Details:</p>
        <table style="background:#f8fafc;border-radius:8px;width:100%;border-collapse:collapse;margin-bottom:20px">
          ${infoRow("Project Name", data.projectName)}
          ${infoRow("PI Number", data.piNumber)}
          ${infoRow("PI Date", data.piDate)}
          ${infoRow("Total Amount", data.piAmount)}
        </table>
        <p style="color:#475569;margin:0 0 20px">You are requested to review the attached Proforma Invoice and provide formal approval or documented feedback to enable further processing.</p>
        <p style="color:#475569;margin:0 0 20px">Please note that subsequent project execution and related workflows are contingent upon receipt of your approval.</p>
        <p style="color:#475569;margin:0 0 20px">For any clarifications, discrepancies, or amendments, kindly coordinate with your designated account representative or respond via the appropriate communication channel.</p>
        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0">
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Please Note:</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px">This is a system-generated communication issued by Rishiraj Media. It is intended solely for the designated recipient. Any unauthorized review, dissemination, or use of this document is strictly prohibited.</p>
        <p style="color:#64748b;font-size:12px;margin:0">Do not reply directly to this email.</p>
      `),
    })
    console.log(`[EMAIL SENT] PI Generated email sent to ${to}`)
  } catch (error) {
    console.error(`[EMAIL ERROR] Failed to send PI Generated email to ${to}`, error)
  }
}

// 2. Material Under Production Stage Email
export async function sendProductionStartedEmail(to: string, data: {
  pocName: string; projectName: string; piNumber: string; productionStartDate: string; appUrl: string
}) {
  const resend = getResend()
  if (!resend) return
  try {
    await resend.emails.send({
      from: FROM, to,
      subject: `System Notification: Production Initiated – ${data.projectName} | Status Update`,
      html: baseTemplate("Production Initiated", `
        <p style="color:#475569;margin:0 0 20px">Dear ${data.pocName},</p>
        <p style="color:#475569;margin:0 0 20px">This is an automated system notification generated by Rishiraj Media.</p>
        <p style="color:#475569;margin:0 0 20px">Please be informed that the materials associated with the project referenced below have been moved to the Production Stage and processing has been initiated as per the approved Proforma Invoice and confirmed specifications.</p>
        <p style="color:#003c71;margin:0 0 12px;font-weight:600">Project Details:</p>
        <table style="background:#f8fafc;border-radius:8px;width:100%;border-collapse:collapse;margin-bottom:20px">
          ${infoRow("Project Name", data.projectName)}
          ${infoRow("Order / PI Reference", data.piNumber)}
          ${infoRow("Production Start Date", data.productionStartDate)}
          ${infoRow("Current Status", "Under Production")}
        </table>
        <p style="color:#475569;margin:0 0 20px">All production activities are being executed in accordance with the approved scope, specifications, and timelines recorded in the system.</p>
        <p style="color:#475569;margin:0 0 20px">At this stage, any modification requests may be subject to feasibility assessment, cost implications, and potential impact on delivery timelines.</p>
        <p style="color:#475569;margin:0 0 20px">You will be notified upon completion of production or in case of any exceptions requiring your attention.</p>
        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0">
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Please Note:</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px">This is a system-generated communication issued by Rishiraj Media for status tracking and audit purposes. The information contained herein is confidential and intended solely for the designated recipient.</p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>No action is required at this stage.</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0">Do not reply directly to this email.</p>
      `),
    })
    console.log(`[EMAIL SENT] Production Started email sent to ${to}`)
  } catch (error) {
    console.error(`[EMAIL ERROR] Failed to send Production Started email to ${to}`, error)
  }
}

// 3. Shipment Dispatched Stage Email (Updated)
export async function sendShipmentDispatchedEmail(to: string, data: {
  pocName: string; projectName: string; piNumber: string; dispatchDate: string; courier: string; deliveryAddress: string; appUrl: string
}) {
  const resend = getResend()
  if (!resend) return
  try {
    await resend.emails.send({
      from: FROM, to,
      subject: `Attach : Challan | System Notification: Material Dispatched – ${data.projectName} | Shipment Details`,
      html: baseTemplate("Material Dispatched", `
        <p style="color:#475569;margin:0 0 20px">Dear ${data.pocName},</p>
        <p style="color:#475569;margin:0 0 20px">This is an automated system notification generated by Rishiraj Media.</p>
        <p style="color:#475569;margin:0 0 20px">Please be informed that the materials associated with the project referenced below have been dispatched from the production facility.</p>
        <p style="color:#003c71;margin:0 0 12px;font-weight:600">Shipment Details:</p>
        <table style="background:#f8fafc;border-radius:8px;width:100%;border-collapse:collapse;margin-bottom:20px">
          ${infoRow("Project Name", data.projectName)}
          ${infoRow("Order / PI Reference", data.piNumber)}
          ${infoRow("Dispatch Date", data.dispatchDate)}
          ${infoRow("Courier / Transport Partner", data.courier)}
          ${infoRow("Delivery Address", data.deliveryAddress)}
        </table>
        <p style="color:#475569;margin:0 0 20px">The shipment is currently in transit. You may track the status through Mailroom.</p>
        ${button("Track Shipment", `${data.appUrl}/projects`)}

        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0">
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Please Note:</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px">This is a system-generated communication issued by Rishiraj Media for operational tracking and audit purposes. The information contained herein is confidential and intended solely for the designated recipient.</p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Action Required:</strong> Please monitor shipment and arrange for receipt.</p>
        <p style="color:#64748b;font-size:12px;margin:0">Do not reply directly to this email.</p>
      `),
    })
    console.log(`[EMAIL SENT] Shipment Dispatched email sent to ${to}`)
  } catch (error) {
    console.error(`[EMAIL ERROR] Failed to send Shipment Dispatched email to ${to}`, error)
  }
}

// 4. Reminder: Pending Purchase Order (PO)
export async function sendPendingPOReminderEmail(to: string, data: {
  pocName: string; projectName: string; piNumber: string; piDate: string; piAmount: string; appUrl: string
}) {
  const resend = getResend()
  if (!resend) return
  try {
    await resend.emails.send({
      from: FROM, to,
      subject: `Attach: PI | Reminder: Pending PO – ${data.projectName} | Action Required`,
      html: baseTemplate("Pending Purchase Order Reminder", `
        <p style="color:#475569;margin:0 0 20px">Dear ${data.pocName},</p>
        <p style="color:#475569;margin:0 0 20px">This is an automated reminder generated by Rishiraj Media.</p>
        <p style="color:#475569;margin:0 0 20px">As per system records, the Purchase Order (PO) for the project referenced below is pending.</p>
        <p style="color:#003c71;margin:0 0 12px;font-weight:600">Reference Details:</p>
        <table style="background:#f8fafc;border-radius:8px;width:100%;border-collapse:collapse;margin-bottom:20px">
          ${infoRow("Project Name", data.projectName)}
          ${infoRow("Proforma Invoice (PI) Number", data.piNumber)}
          ${infoRow("PI Date", data.piDate)}
          ${infoRow("PI Amount", data.piAmount)}
        </table>
        <p style="color:#475569;margin:0 0 20px">You are requested to share the PO at the earliest to avoid any delays.</p>
        <p style="color:#475569;margin:0 0 20px">In case the PO has already been issued, kindly disregard this notification or share the relevant reference details for system reconciliation.</p>
        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0">
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Please Note:</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px">This is a system-generated reminder issued by Rishiraj Media for process compliance and audit tracking. The information contained herein is confidential and intended solely for the designated recipient.</p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Action Required:</strong> Submission of Purchase Order</p>
        <p style="color:#64748b;font-size:12px;margin:0">Do not reply directly to this email.</p>
      `),
    })
    console.log(`[EMAIL SENT] Pending PO Reminder email sent to ${to}`)
  } catch (error) {
    console.error(`[EMAIL ERROR] Failed to send Pending PO Reminder email to ${to}`, error)
  }
}

// 5. Reminder: Outstanding Invoice Payment
export async function sendOutstandingPaymentReminderEmail(to: string, data: {
  pocName: string; projectName: string; invoiceNumber: string; invoiceDate: string; outstandingAmount: string; appUrl: string; referenceType?: string
}) {
  const resend = getResend()
  if (!resend) return
  try {
    await resend.emails.send({
      from: FROM, to,
      subject: `Attach ${data.referenceType || 'Invoice'} | Reminder: Outstanding Payment Due – ${data.invoiceNumber} | Attention Required`,
      html: baseTemplate("Outstanding Payment Reminder", `
        <p style="color:#475569;margin:0 0 20px">Dear ${data.pocName},</p>
        <p style="color:#475569;margin:0 0 20px">This is an automated reminder generated by Rishiraj Media.</p>
        <p style="color:#475569;margin:0 0 20px">As per our records, the following ${data.referenceType?.toLowerCase() || 'invoice'} remains outstanding for very long.</p>
        <p style="color:#003c71;margin:0 0 12px;font-weight:600">${data.referenceType || 'Invoice'} Details:</p>
        <table style="background:#f8fafc;border-radius:8px;width:100%;border-collapse:collapse;margin-bottom:20px">
          ${infoRow("Project Name", data.projectName)}
          ${infoRow(`${data.referenceType || 'Invoice'} Number`, data.invoiceNumber)}
          ${infoRow(`${data.referenceType || 'Invoice'} Date`, data.invoiceDate)}
          ${infoRow("Outstanding Amount", data.outstandingAmount)}
        </table>
        <p style="color:#475569;margin:0 0 20px">We request you to arrange for payment at the earliest.</p>
        <p style="color:#475569;margin:0 0 20px">If payment has already been processed, kindly disregard this notification or share transaction details for reconciliation.</p>
        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0">
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Please Note:</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px">This is a system-generated reminder issued by Rishiraj Media for financial compliance and audit purposes. The information contained herein is confidential and intended solely for the designated recipient.</p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Action Required:</strong> Payment of outstanding dues</p>
        <p style="color:#64748b;font-size:12px;margin:0">Do not reply directly to this email.</p>
      `),
    })
    console.log(`[EMAIL SENT] Outstanding Payment Reminder email sent to ${to}`)
  } catch (error) {
    console.error(`[EMAIL ERROR] Failed to send Outstanding Payment Reminder email to ${to}`, error)
  }
}

// PI Verified – sent to POC
export async function sendPIVerifiedEmail(to: string, data: {
  pocName: string; projectName: string; piNumber: string; appUrl: string
}) {
  const resend = getResend()
  if (!resend) return
  try {
    await resend.emails.send({
      from: FROM, to,
      subject: `System Notification: PI Verified – ${data.projectName} | Action Required`,
      html: baseTemplate("Proforma Invoice Verified", `
        <p style="color:#475569;margin:0 0 20px">Dear ${data.pocName},</p>
        <p style="color:#475569;margin:0 0 20px">This is an automated system notification generated by Rishiraj Media.</p>
        <p style="color:#475569;margin:0 0 20px">Please be informed that your Proforma Invoice has been reviewed and verified by the Admin. The project is now cleared to proceed to the next stage.</p>
        <p style="color:#003c71;margin:0 0 12px;font-weight:600">Reference Details:</p>
        <table style="background:#f8fafc;border-radius:8px;width:100%;border-collapse:collapse;margin-bottom:20px">
          ${infoRow("Project Name", data.projectName)}
          ${infoRow("PI Number", data.piNumber)}
          ${infoRow("Status", "Verified")}
        </table>
        <p style="color:#475569;margin:0 0 20px">You are requested to share the verified PI with the client and obtain the Purchase Order (PO) to enable further processing.</p>
        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0">
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Please Note:</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px">This is a system-generated communication issued by Rishiraj Media. It is intended solely for the designated recipient.</p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Action Required:</strong> Share PI with client and obtain Purchase Order.</p>
        <p style="color:#64748b;font-size:12px;margin:0">Do not reply directly to this email.</p>
      `),
    })
    console.log(`[EMAIL SENT] PI Verified email sent to ${to}`)
  } catch (error) {
    console.error(`[EMAIL ERROR] Failed to send PI Verified email to ${to}`, error)
  }
}

// PI Rejected – sent to POC
export async function sendPIRejectedEmail(to: string, data: {
  pocName: string; projectName: string; piNumber: string; reason?: string; appUrl: string
}) {
  const resend = getResend()
  if (!resend) return
  try {
    await resend.emails.send({
      from: FROM, to,
      subject: `System Notification: PI Rejected – ${data.projectName} | Action Required`,
      html: baseTemplate("Proforma Invoice Rejected", `
        <p style="color:#475569;margin:0 0 20px">Dear ${data.pocName},</p>
        <p style="color:#475569;margin:0 0 20px">This is an automated system notification generated by Rishiraj Media.</p>
        <p style="color:#475569;margin:0 0 20px">Please be informed that your Proforma Invoice has been reviewed and rejected. The PI cannot be processed as submitted.</p>
        <p style="color:#003c71;margin:0 0 12px;font-weight:600">Reference Details:</p>
        <table style="background:#f8fafc;border-radius:8px;width:100%;border-collapse:collapse;margin-bottom:20px">
          ${infoRow("Project Name", data.projectName)}
          ${infoRow("PI Number", data.piNumber)}
          ${infoRow("Status", "Rejected")}
          ${data.reason ? infoRow("Reason for Rejection", data.reason) : ""}
        </table>
        <p style="color:#475569;margin:0 0 20px">You are requested to review the reason for rejection and regenerate the PI with the necessary corrections at the earliest.</p>
        <p style="color:#475569;margin:0 0 20px">For any clarifications, kindly coordinate with your designated account representative.</p>
        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0">
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Please Note:</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px">This is a system-generated communication issued by Rishiraj Media. It is intended solely for the designated recipient.</p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Action Required:</strong> Regenerate PI with corrections.</p>
        <p style="color:#64748b;font-size:12px;margin:0">Do not reply directly to this email.</p>
      `),
    })
    console.log(`[EMAIL SENT] PI Rejected email sent to ${to}`)
  } catch (error) {
    console.error(`[EMAIL ERROR] Failed to send PI Rejected email to ${to}`, error)
  }
}

// Admin – New Project Submitted for Approval
export async function sendAdminNewProjectEmail(to: string, data: {
  adminName: string; projectName: string; projectId: string; pocName: string; clientName?: string; appUrl: string
}) {
  const resend = getResend()
  if (!resend) return
  try {
    await resend.emails.send({
      from: FROM, to,
      subject: `Action Required: New Project Submitted – ${data.projectName} | Approval Pending`,
      html: baseTemplate("New Project Submitted for Approval", `
        <p style="color:#475569;margin:0 0 20px">Dear ${data.adminName},</p>
        <p style="color:#475569;margin:0 0 20px">This is an automated system notification generated by Rishiraj Media.</p>
        <p style="color:#475569;margin:0 0 20px">A new project has been submitted and is pending your review and approval.</p>
        <p style="color:#003c71;margin:0 0 12px;font-weight:600">Project Details:</p>
        <table style="background:#f8fafc;border-radius:8px;width:100%;border-collapse:collapse;margin-bottom:20px">
          ${infoRow("Project Name", data.projectName)}
          ${infoRow("Project ID", data.projectId)}
          ${infoRow("Submitted By", data.pocName)}
          ${data.clientName ? infoRow("On Behalf Of", data.clientName) : ""}
        </table>
        <p style="color:#475569;margin:0 0 20px">You are requested to review the project details and approve or reject the request at the earliest to avoid delays.</p>
        ${button("Review & Approve", `${data.appUrl}/approvals`)}
        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0">
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Please Note:</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px">This is a system-generated communication issued by Rishiraj Media for process compliance and audit tracking. The information contained herein is confidential and intended solely for the designated recipient.</p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Action Required:</strong> Review and approve or reject the project.</p>
        <p style="color:#64748b;font-size:12px;margin:0">Do not reply directly to this email.</p>
      `),
    })
    console.log(`[EMAIL SENT] Admin new project email sent to ${to}`)
  } catch (error) {
    console.error(`[EMAIL ERROR] Failed to send admin new project email to ${to}`, error)
  }
}

// Admin – PI Pending Verification
export async function sendAdminPIPendingEmail(to: string, data: {
  adminName: string; projectName: string; piNumber: string; pocName: string; appUrl: string
}) {
  const resend = getResend()
  if (!resend) return
  try {
    await resend.emails.send({
      from: FROM, to,
      subject: `Action Required: PI Pending Verification – ${data.projectName} | Review Required`,
      html: baseTemplate("Proforma Invoice Pending Verification", `
        <p style="color:#475569;margin:0 0 20px">Dear ${data.adminName},</p>
        <p style="color:#475569;margin:0 0 20px">This is an automated system notification generated by Rishiraj Media.</p>
        <p style="color:#475569;margin:0 0 20px">A Proforma Invoice has been generated and is pending your verification.</p>
        <p style="color:#003c71;margin:0 0 12px;font-weight:600">Reference Details:</p>
        <table style="background:#f8fafc;border-radius:8px;width:100%;border-collapse:collapse;margin-bottom:20px">
          ${infoRow("Project Name", data.projectName)}
          ${infoRow("PI Number", data.piNumber)}
          ${infoRow("Generated By", data.pocName)}
        </table>
        <p style="color:#475569;margin:0 0 20px">You are requested to review the PI and verify or reject it at the earliest to enable further project processing.</p>
        ${button("Verify PI", `${data.appUrl}/projects`)}
        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0">
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Please Note:</strong></p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px">This is a system-generated communication issued by Rishiraj Media for process compliance and audit tracking. The information contained herein is confidential and intended solely for the designated recipient.</p>
        <p style="color:#64748b;font-size:12px;margin:0 0 8px"><strong>Action Required:</strong> Verify or reject the Proforma Invoice.</p>
        <p style="color:#64748b;font-size:12px;margin:0">Do not reply directly to this email.</p>
      `),
    })
    console.log(`[EMAIL SENT] Admin PI pending email sent to ${to}`)
  } catch (error) {
    console.error(`[EMAIL ERROR] Failed to send admin PI pending email to ${to}`, error)
  }
}
