import nodemailer from "nodemailer"
import { Resend } from "resend"

const resend = new Resend("re_VxU7DPQ9_4kjuwD2Qpu91ZVUw7f1iz8kx")
//const resend = new Resend(process.env.RESEND_API_KEY)

// Create reusable nodemailer transporter for cPanel SMTP fallback
const createTransporter = () => {
  return nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: Number.parseInt(process.env.SMTP_PORT || "587"),
    secure: process.env.SMTP_SECURE === "true",
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASSWORD,
    },
  })
}
/* const createTransporter = () => {
  return nodemailer.createTransport({  
    host: "smtp.resend.com",
    port: 587,
    secure: false,
    auth: {
      user: "startup@aksoftech.com.ng",
      pass: "re_VxU7DPQ9_4kjuwD2Qpu91ZVUw7f1iz8kx",
    },
  })
} */

export interface InquiryFormData {
  name: string
  email: string
  phone: string
  service?: string
  message: string
  subject?: string
}

// Format inquiry data into a professional HTML email
const formatInquiryEmailHTML = (data: InquiryFormData, source: "home" | "contact"): string => {
  const formattedDate = new Date().toLocaleString("en-NG", { timeZone: "Africa/Lagos" })

  return `
    <!DOCTYPE html>
    <html>
      <head>
        <style>
          body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; }
          .container { max-width: 600px; margin: 0 auto; padding: 20px; background-color: #f9fafb; border-radius: 8px; }
          .header { background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%); padding: 30px; border-radius: 8px 8px 0 0; text-align: center; }
          .header h1 { color: #0369a1; margin: 0; font-size: 28px; }
          .header p { color: #0c4a6e; margin: 5px 0 0 0; font-size: 14px; }
          .content { background-color: #fff; padding: 30px; border-radius: 0 0 8px 8px; }
          .section { margin-bottom: 25px; }
          .section-title { color: #0369a1; font-size: 16px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 10px; border-bottom: 2px solid #e0f2fe; padding-bottom: 8px; }
          .info-row { margin-bottom: 12px; display: flex; }
          .info-label { font-weight: 600; color: #0c4a6e; min-width: 120px; }
          .info-value { color: #333; flex: 1; }
          .message-box { background-color: #f0f9ff; border-left: 4px solid #0369a1; padding: 15px; border-radius: 4px; margin-top: 10px; }
          .footer { margin-top: 30px; padding-top: 20px; border-top: 1px solid #e5e7eb; text-align: center; font-size: 12px; color: #6b7280; }
          .company-name { color: #0369a1; font-weight: 700; }
          .source-badge { display: inline-block; background-color: #0369a1; color: white; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; margin-top: 15px; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>New Inquiry Received</h1>
            <p>From <span class="company-name">AKSOF TECHNOLOGY SERVICES</span> Website</p>
          </div>
          
          <div class="content">
            <div class="section">
              <div class="section-title">Sender Information</div>
              <div class="info-row">
                <span class="info-label">Full Name:</span>
                <span class="info-value">${escapeHtml(data.name)}</span>
              </div>
              <div class="info-row">
                <span class="info-label">Email:</span>
                <span class="info-value"><a href="mailto:${escapeHtml(data.email)}">${escapeHtml(data.email)}</a></span>
              </div>
              <div class="info-row">
                <span class="info-label">Phone:</span>
                <span class="info-value"><a href="tel:${escapeHtml(data.phone)}">${escapeHtml(data.phone)}</a></span>
              </div>
            </div>

            ${
              data.service
                ? `
            <div class="section">
              <div class="section-title">Service of Interest</div>
              <div class="info-value">${escapeHtml(data.service)}</div>
            </div>
            `
                : ""
            }

            ${
              data.subject
                ? `
            <div class="section">
              <div class="section-title">Subject</div>
              <div class="info-value">${escapeHtml(data.subject)}</div>
            </div>
            `
                : ""
            }

            <div class="section">
              <div class="section-title">Message</div>
              <div class="message-box">
                ${escapeHtml(data.message).replace(/\n/g, "<br />")}
              </div>
            </div>

            <div class="section">
              <div class="section-title">Submission Details</div>
              <div class="info-row">
                <span class="info-label">Source:</span>
                <span class="info-value">${source === "home" ? "Homepage Inquiry Form" : "Contact Page Form"}</span>
              </div>
              <div class="info-row">
                <span class="info-label">Submitted:</span>
                <span class="info-value">${formattedDate} (WAT)</span>
              </div>
            </div>

            <div style="text-align: center;">
              <span class="source-badge">${source === "home" ? "🏠 HOMEPAGE" : "📧 CONTACT PAGE"}</span>
            </div>

            <div class="footer">
              <p>This is an automated email from <span class="company-name">AKSOF TECHNOLOGY SERVICES</span> website.</p>
              <p>Please reply directly to the sender's email address or contact them at the provided phone number.</p>
            </div>
          </div>
        </div>
      </body>
    </html>
  `
}

// Helper function to escape HTML characters
function escapeHtml(text: string): string {
  const map: { [key: string]: string } = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;",
    "'": "&#039;",
  }
  return text.replace(/[&<>"']/g, (m) => map[m])
}

// Main email sending function
export const sendInquiryEmail = async (
  data: InquiryFormData,
  source: "home" | "contact" = "home",
): Promise<{ success: boolean; message: string }> => {
  try {
    const transporter = createTransporter()

    // Verify connection
    await transporter.verify()

    // Send email to company
    await transporter.sendMail({
      from: process.env.SMTP_FROM_EMAIL || process.env.SMTP_USER,
      to: "enquiry@aksoftech.com.ng",
      subject: `New Inquiry: ${data.subject || data.service || "General Inquiry"} - From ${data.name}`,
      html: formatInquiryEmailHTML(data, source),
      replyTo: data.email,
    })

    // Send confirmation email to user
    const confirmationHTML = `
      <!DOCTYPE html>
      <html>
        <head>
          <style>
            body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; background-color: #f9fafb; border-radius: 8px; }
            .header { background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%); padding: 30px; border-radius: 8px 8px 0 0; text-align: center; }
            .header h1 { color: #0369a1; margin: 0; font-size: 24px; }
            .content { background-color: #fff; padding: 30px; border-radius: 0 0 8px 8px; }
            .section { margin-bottom: 20px; }
            .company-name { color: #0369a1; font-weight: 700; }
            .footer { margin-top: 20px; padding-top: 15px; border-top: 1px solid #e5e7eb; text-align: center; font-size: 12px; color: #6b7280; }
            .contact-info { background-color: #f0f9ff; padding: 15px; border-radius: 4px; margin-top: 15px; }
          </style>
        </head>
        <body>
          <div class="container">
            <div class="header">
              <h1>Thank You!</h1>
            </div>
            
            <div class="content">
              <div class="section">
                <p>Dear ${escapeHtml(data.name)},</p>
                <p>We have received your inquiry and appreciate your interest in <span class="company-name">AKSOF TECHNOLOGY SERVICES</span>.</p>
                <p>Our team will review your message and get back to you as soon as possible, usually within 24 business hours.</p>
              </div>

              <div class="section">
                <p>In the meantime, if you have any urgent matters, please feel free to contact us directly:</p>
                <div class="contact-info">
                  <p><strong>📧 Email:</strong> enquiry@aksoftech.com.ng</p>
                  <p><strong>📱 Phone:</strong> (+234) 707 266 3977</p>
                  <p><strong>⏰ Business Hours:</strong> Monday - Friday, 9AM - 5PM WAT</p>
                </div>
              </div>

              <div class="section">
                <p>Best regards,</p>
                <p><strong><span class="company-name">AKSOF TECHNOLOGY SERVICES</span></strong></p>
              </div>

              <div class="footer">
                <p>This is an automated confirmation email. Please do not reply to this email.</p>
              </div>
            </div>
          </div>
        </body>
      </html>
    `

    await transporter.sendMail({
      from: process.env.SMTP_FROM_EMAIL || process.env.SMTP_USER,
      to: data.email,
      subject: "Inquiry Confirmation - AKSOF TECHNOLOGY SERVICES",
      html: confirmationHTML,
    })

    return {
      success: true,
      message: "Your inquiry has been sent successfully!",
    }
  } catch (error) {
    console.error("Email sending error:", error)
    return {
      success: false,
      message: "Failed to send inquiry. Please try again or contact us directly.",
    }
  }
}
