import nodemailer from 'nodemailer'
import refreshTokenHelper from "../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../utils/errorHandlingHelper"
import getTokenHelper from "../../utils/getTokenHelper"
import fetchHelper from "../../utils/fetchHelper"

interface ReturnLine {
  productName: string
  productValue: string
  qtyEntered: number
}

const formatDate = (dateStr: string, lang: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const isGerman = lang.startsWith('de')
  return date.toLocaleDateString(isGerman ? 'de-DE' : 'en-US', { day: '2-digit', month: '2-digit', year: 'numeric' })
}

const generateHtmlNotificationDE = (
  rmaName: string,
  returnDate: string,
  reason: string,
  customerName: string,
  shipmentNo: string,
  orderNo: string,
  externalOrderId: string,
  lines: ReturnLine[]
) => {
  const linesHtml = lines.map(line => `
    <tr>
      <td style="padding: 10px 12px; border-bottom: 1px solid #e0e0e0;">${line.productValue}</td>
      <td style="padding: 10px 12px; border-bottom: 1px solid #e0e0e0;">${line.productName}</td>
      <td style="padding: 10px 12px; border-bottom: 1px solid #e0e0e0; text-align: center;">${line.qtyEntered}</td>
    </tr>
  `).join('')

  return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Retoure-Benachrichtigung - ${rmaName}</title>
</head>
<body style="margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; font-size: 14px; line-height: 1.6; color: #333333; background-color: #f4f4f4;">
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color: #f4f4f4;">
    <tr>
      <td style="padding: 20px 0;">
        <table role="presentation" width="600" cellspacing="0" cellpadding="0" style="margin: 0 auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
          <!-- Header -->
          <tr>
            <td style="background-color: #f59e0b; padding: 30px 40px; text-align: center;">
              <h1 style="margin: 0; color: #ffffff; font-size: 24px; font-weight: 600;">Retoure eingegangen</h1>
              <p style="margin: 10px 0 0 0; color: #ffffff; font-size: 16px;">${rmaName}</p>
            </td>
          </tr>

          <!-- Content -->
          <tr>
            <td style="padding: 40px;">
              <p style="margin: 0 0 20px 0;">
                Eine neue Retoure wurde erfasst. Nachfolgend finden Sie die Details:
              </p>

              <!-- Return Details Table -->
              <table role="presentation" cellspacing="0" cellpadding="0" style="width: 100%; border-collapse: collapse; margin: 20px 0; border: 1px solid #e0e0e0; border-radius: 6px;">
                <tr style="background-color: #f8f9fa;">
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0; font-weight: 600; width: 140px;">Datum</td>
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0;">${returnDate}</td>
                </tr>
                <tr>
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0; font-weight: 600;">Kunde</td>
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0;">${customerName}</td>
                </tr>
                <tr style="background-color: #f8f9fa;">
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0; font-weight: 600;">Bestellung</td>
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0;">${orderNo}</td>
                </tr>
                ${externalOrderId ? `<tr>
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0; font-weight: 600;">Externe Bestellnr.</td>
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0;">${externalOrderId}</td>
                </tr>` : ''}
                <tr style="background-color: #f8f9fa;">
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0; font-weight: 600;">Lieferschein</td>
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0;">${shipmentNo}</td>
                </tr>
                <tr>
                  <td style="padding: 12px 16px; font-weight: 600;">Rückgabegrund</td>
                  <td style="padding: 12px 16px; font-weight: 600; color: #f59e0b;">${reason}</td>
                </tr>
              </table>

              <h3 style="margin: 30px 0 15px 0; font-size: 16px;">Retournierte Artikel:</h3>

              <!-- Articles Table -->
              <table role="presentation" cellspacing="0" cellpadding="0" style="width: 100%; border-collapse: collapse; border: 1px solid #e0e0e0; border-radius: 6px;">
                <thead>
                  <tr style="background-color: #f8f9fa;">
                    <th style="padding: 12px; border-bottom: 2px solid #e0e0e0; text-align: left; font-weight: 600;">Artikelnr.</th>
                    <th style="padding: 12px; border-bottom: 2px solid #e0e0e0; text-align: left; font-weight: 600;">Bezeichnung</th>
                    <th style="padding: 12px; border-bottom: 2px solid #e0e0e0; text-align: center; font-weight: 600;">Menge</th>
                  </tr>
                </thead>
                <tbody>
                  ${linesHtml}
                </tbody>
              </table>
            </td>
          </tr>

          <!-- Footer -->
          <tr>
            <td style="background-color: #f8f9fa; padding: 20px 40px; text-align: center; border-top: 1px solid #eeeeee;">
              <p style="margin: 0; font-size: 12px; color: #888888;">
                Diese E-Mail wurde automatisch versendet. Bitte antworten Sie nicht direkt auf diese E-Mail.
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
`
}

const generateHtmlNotificationEN = (
  rmaName: string,
  returnDate: string,
  reason: string,
  customerName: string,
  shipmentNo: string,
  orderNo: string,
  externalOrderId: string,
  lines: ReturnLine[]
) => {
  const linesHtml = lines.map(line => `
    <tr>
      <td style="padding: 10px 12px; border-bottom: 1px solid #e0e0e0;">${line.productValue}</td>
      <td style="padding: 10px 12px; border-bottom: 1px solid #e0e0e0;">${line.productName}</td>
      <td style="padding: 10px 12px; border-bottom: 1px solid #e0e0e0; text-align: center;">${line.qtyEntered}</td>
    </tr>
  `).join('')

  return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Return Notification - ${rmaName}</title>
</head>
<body style="margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; font-size: 14px; line-height: 1.6; color: #333333; background-color: #f4f4f4;">
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color: #f4f4f4;">
    <tr>
      <td style="padding: 20px 0;">
        <table role="presentation" width="600" cellspacing="0" cellpadding="0" style="margin: 0 auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
          <!-- Header -->
          <tr>
            <td style="background-color: #f59e0b; padding: 30px 40px; text-align: center;">
              <h1 style="margin: 0; color: #ffffff; font-size: 24px; font-weight: 600;">Return Received</h1>
              <p style="margin: 10px 0 0 0; color: #ffffff; font-size: 16px;">${rmaName}</p>
            </td>
          </tr>

          <!-- Content -->
          <tr>
            <td style="padding: 40px;">
              <p style="margin: 0 0 20px 0;">
                A new return has been processed. Please find the details below:
              </p>

              <!-- Return Details Table -->
              <table role="presentation" cellspacing="0" cellpadding="0" style="width: 100%; border-collapse: collapse; margin: 20px 0; border: 1px solid #e0e0e0; border-radius: 6px;">
                <tr style="background-color: #f8f9fa;">
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0; font-weight: 600; width: 140px;">Date</td>
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0;">${returnDate}</td>
                </tr>
                <tr>
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0; font-weight: 600;">Customer</td>
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0;">${customerName}</td>
                </tr>
                <tr style="background-color: #f8f9fa;">
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0; font-weight: 600;">Order</td>
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0;">${orderNo}</td>
                </tr>
                ${externalOrderId ? `<tr>
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0; font-weight: 600;">External Order No.</td>
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0;">${externalOrderId}</td>
                </tr>` : ''}
                <tr style="background-color: #f8f9fa;">
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0; font-weight: 600;">Shipment</td>
                  <td style="padding: 12px 16px; border-bottom: 1px solid #e0e0e0;">${shipmentNo}</td>
                </tr>
                <tr>
                  <td style="padding: 12px 16px; font-weight: 600;">Return Reason</td>
                  <td style="padding: 12px 16px; font-weight: 600; color: #f59e0b;">${reason}</td>
                </tr>
              </table>

              <h3 style="margin: 30px 0 15px 0; font-size: 16px;">Returned Articles:</h3>

              <!-- Articles Table -->
              <table role="presentation" cellspacing="0" cellpadding="0" style="width: 100%; border-collapse: collapse; border: 1px solid #e0e0e0; border-radius: 6px;">
                <thead>
                  <tr style="background-color: #f8f9fa;">
                    <th style="padding: 12px; border-bottom: 2px solid #e0e0e0; text-align: left; font-weight: 600;">Article No.</th>
                    <th style="padding: 12px; border-bottom: 2px solid #e0e0e0; text-align: left; font-weight: 600;">Description</th>
                    <th style="padding: 12px; border-bottom: 2px solid #e0e0e0; text-align: center; font-weight: 600;">Qty</th>
                  </tr>
                </thead>
                <tbody>
                  ${linesHtml}
                </tbody>
              </table>
            </td>
          </tr>

          <!-- Footer -->
          <tr>
            <td style="background-color: #f8f9fa; padding: 20px 40px; text-align: center; border-top: 1px solid #eeeeee;">
              <p style="margin: 0; font-size: 12px; color: #888888;">
                This email was sent automatically. Please do not reply directly to this email.
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
`
}

const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = { status: 200, message: 'Return notification sent successfully' }
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)

  const {
    organizationId,
    rmaDocumentNo,
    returnDate,
    reason,
    customerName,
    shipmentNo,
    orderNo,
    externalOrderId,
    lines,
    testOnly,
    images
  } = body

  // Use the RMA DocumentNo from the API response (e.g., "10000123")
  const formattedRmaName = `RMA ${rmaDocumentNo}`

  if (!organizationId || !rmaDocumentNo || !lines || lines.length === 0) {
    return { status: 400, message: 'Missing required fields' }
  }

  let toEmail = 'info@logyou.de'
  let partnerLanguage = 'de_DE'
  let returnEmail = ''

  // If not test only, get the organization's BPartner email
  if (!testOnly) {
    // Get the organization's BPartner to find the email
    const orgRes: any = await fetchHelper(
      event,
      `models/ad_org/${organizationId}?$select=C_BPartner_ID`,
      'GET',
      token,
      null
    )

    const orgBPartnerId = orgRes?.C_BPartner_ID?.id
    if (!orgBPartnerId) {
      return { status: 400, message: 'Organization has no associated BPartner' }
    }

    // Get the BPartner email, language, and return_email
    const bpartnerRes: any = await fetchHelper(
      event,
      `models/c_bpartner/${orgBPartnerId}?$select=EMail,AD_Language,return_email`,
      'GET',
      token,
      null
    )

    toEmail = bpartnerRes?.EMail
    if (!toEmail) {
      return { status: 400, message: 'Organization BPartner has no email configured' }
    }

    partnerLanguage = bpartnerRes?.AD_Language?.id || 'de_DE'
    returnEmail = bpartnerRes?.return_email || ''
  }
  const isGerman = partnerLanguage.startsWith('de')

  // Format the return date
  const formattedDate = formatDate(returnDate, partnerLanguage)

  // Generate HTML email based on language
  const htmlContent = isGerman
    ? generateHtmlNotificationDE(formattedRmaName, formattedDate, reason, customerName, shipmentNo, orderNo || '', externalOrderId || '', lines)
    : generateHtmlNotificationEN(formattedRmaName, formattedDate, reason, customerName, shipmentNo, orderNo || '', externalOrderId || '', lines)

  // Create email subject
  const subject = isGerman
    ? `Retoure-Benachrichtigung: ${formattedRmaName}`
    : `Return Notification: ${formattedRmaName}`

  // Plain text version
  const textContent = isGerman
    ? `Retoure ${formattedRmaName} wurde verarbeitet.\n\nKunde: ${customerName}\nBestellung: ${orderNo || '-'}${externalOrderId ? '\nExterne Bestellnr.: ' + externalOrderId : ''}\nLieferschein: ${shipmentNo}\nRückgabegrund: ${reason}\nDatum: ${formattedDate}\n\nArtikel:\n${lines.map((l: ReturnLine) => `- ${l.productValue}: ${l.productName} (${l.qtyEntered}x)`).join('\n')}`
    : `Return ${formattedRmaName} has been processed.\n\nCustomer: ${customerName}\nOrder: ${orderNo || '-'}${externalOrderId ? '\nExternal Order No.: ' + externalOrderId : ''}\nShipment: ${shipmentNo}\nReturn Reason: ${reason}\nDate: ${formattedDate}\n\nArticles:\n${lines.map((l: ReturnLine) => `- ${l.productValue}: ${l.productName} (${l.qtyEntered}x)`).join('\n')}`

  // Create transporter using localhost as smarthost on port 25
  const transporter = nodemailer.createTransport({
    host: 'localhost',
    port: 25,
    secure: false,
    tls: {
      rejectUnauthorized: false
    }
  })

  // Build email options
  const emailOptions: any = {
    from: 'no-reply@logyou.de',
    to: toEmail,
    subject: subject,
    text: textContent,
    html: htmlContent
  }

  // Only add CC if not test mode
  if (!testOnly) {
    const ccList = ['info@logyou.de']
    if (returnEmail) {
      ccList.push(returnEmail)
    }
    emailOptions.cc = ccList.join(', ')
  }

  // Add image attachments if provided
  if (images && Array.isArray(images) && images.length > 0) {
    emailOptions.attachments = images.map((imageData: string, index: number) => {
      // Remove the data URL prefix (e.g., "data:image/jpeg;base64,")
      const base64Data = imageData.replace(/^data:image\/\w+;base64,/, '')
      const imageBuffer = Buffer.from(base64Data, 'base64')

      // Determine file extension from data URL
      const mimeMatch = imageData.match(/^data:image\/(\w+);base64,/)
      const extension = mimeMatch ? mimeMatch[1] : 'jpg'

      return {
        filename: `retoure-bild-${index + 1}.${extension}`,
        content: imageBuffer,
        contentType: `image/${extension}`
      }
    })
  }

  // Send email — THROW on failure (the client's success toast fires unless
  // the request rejects; a 200 body with status:500 read as "sent")
  try {
    await transporter.sendMail(emailOptions)
  } catch (err: any) {
    console.error('Email send error:', err)
    throw createError({
      statusCode: 500,
      statusMessage: `Failed to send return notification: ${err.message}`
    })
  }

  return data
}

export default defineEventHandler(async (event) => {
  // Auth-only retry; errors are THROWN (the old wrapper returned the error
  // object as an HTTP 200 body, which the client reported as "sent").
  return await withAuthRetry(event, handleFunc)
})
