import { Resend } from "resend"

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

interface SendEmailOptions {
  subject: string
  body: string
  replyTo?: string
}

export async function sendEmail({ subject, body, replyTo }: SendEmailOptions) {
  try {
    // TEMPORARY: Using verified email until vazofoundation.org is verified in Resend
    // Once verified, change this to: info@vazofoundation.org
    const recipientEmail = "hbsolutionsptyltd@gmail.com"

    const { data, error } = await resend.emails.send({
      from: "VAZO Foundation <onboarding@resend.dev>",
      to: [recipientEmail],
      subject: `[VAZO] ${subject}`,
      html: body,
      replyTo: replyTo,
    })

    if (error) {
      console.error("Email error:", error)
      throw new Error(error.message)
    }

    console.log(`Email sent successfully to: ${recipientEmail}`)
    return data
  } catch (error) {
    console.error("Email error:", error)
    throw error
  }
}

export function formatFormDataAsHTML(data: Record<string, any>): string {
  const formattedData = Object.entries(data)
    .filter(([_, value]) => value !== null && value !== undefined && value !== "")
    .map(([key, value]) => {
      const formattedKey = key
        .replace(/([A-Z])/g, " $1")
        .replace(/^./, (str) => str.toUpperCase())
        .trim()

      let formattedValue = value
      if (typeof value === "boolean") {
        formattedValue = value ? "Yes" : "No"
      } else if (Array.isArray(value)) {
        formattedValue = value.join(", ")
      }

      return `
        <tr>
          <td style="padding: 12px; border: 1px solid #e5e7eb; background-color: #f9fafb; font-weight: 600; width: 200px;">${formattedKey}</td>
          <td style="padding: 12px; border: 1px solid #e5e7eb;">${formattedValue}</td>
        </tr>
      `
    })
    .join("")

  return `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
      </head>
      <body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #374151; background-color: #f3f4f6; margin: 0; padding: 20px;">
        <div style="max-width: 600px; margin: 0 auto; background-color: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);">
          <div style="background: linear-gradient(135deg, #FF6B35 0%, #FF8E53 100%); padding: 30px; text-align: center;">
            <h1 style="color: white; margin: 0; font-size: 24px; font-weight: 700;">VAZO Foundation</h1>
            <p style="color: #fff; margin: 8px 0 0 0; font-size: 14px;">New Form Submission</p>
          </div>
          
          <div style="background-color: #FEF3C7; border-left: 4px solid #F59E0B; padding: 15px; margin: 20px 20px 0 20px;">
            <p style="margin: 0; color: #92400E; font-weight: 600; font-size: 14px;">📧 Temporary Email Routing</p>
            <p style="margin: 8px 0 0 0; color: #92400E; font-size: 13px;">
              This email should be forwarded to: <strong>info@vazofoundation.org</strong><br>
              Once domain is verified in Resend, emails will go directly there.
            </p>
          </div>

          <div style="padding: 30px;">
            <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
              ${formattedData}
            </table>
            <div style="margin-top: 30px; padding-top: 20px; border-top: 2px solid #e5e7eb; text-align: center; color: #6b7280; font-size: 12px;">
              <p style="margin: 0;">This is an automated message from VAZO Foundation</p>
              <p style="margin: 8px 0 0 0;">Received on ${new Date().toLocaleString("en-ZA", { timeZone: "Africa/Johannesburg" })}</p>
            </div>
          </div>
        </div>
      </body>
    </html>
  `
}
