package services

import (
	"crypto/tls"
	"fmt"
	"log"
	"net/smtp"
	"strconv"
)

type EmailService struct {
	smtpHost     string
	smtpPort     string
	smtpUsername string
	smtpPassword string
	fromEmail    string
	fromName     string
}

func NewEmailService(smtpHost, smtpPort, smtpUsername, smtpPassword, fromEmail, fromName string) *EmailService {
	return &EmailService{
		smtpHost:     smtpHost,
		smtpPort:     smtpPort,
		smtpUsername: smtpUsername,
		smtpPassword: smtpPassword,
		fromEmail:    fromEmail,
		fromName:     fromName,
	}
}

func (s *EmailService) SendOTP(email, otp string) error {
	log.Printf("SendOTP: Attempting to send OTP to %s via %s:%s", email, s.smtpHost, s.smtpPort)

	// Validate SMTP configuration
	if s.smtpHost == "" || s.smtpPort == "" {
		log.Printf("SendOTP: SMTP configuration missing - Host: %s, Port: %s", s.smtpHost, s.smtpPort)
		return fmt.Errorf("SMTP configuration is missing")
	}

	if s.smtpUsername == "" || s.smtpPassword == "" {
		log.Printf("SendOTP: SMTP credentials missing")
		return fmt.Errorf("SMTP credentials are missing")
	}

	// Convert port to int
	port, err := strconv.Atoi(s.smtpPort)
	if err != nil {
		log.Printf("SendOTP: Invalid SMTP port %s: %v", s.smtpPort, err)
		return fmt.Errorf("invalid SMTP port: %w", err)
	}

	// Setup authentication
	auth := smtp.PlainAuth("", s.smtpUsername, s.smtpPassword, s.smtpHost)
	log.Printf("SendOTP: SMTP authentication configured for %s", s.smtpHost)

	// Email content
	subject := "Password Reset Verification Code"
	htmlBody := fmt.Sprintf(`<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Password Reset Verification</title>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background-color: #f5f7fa; line-height: 1.6;">
    <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%%" style="background-color: #f5f7fa; padding: 40px 20px;">
        <tr>
            <td align="center">
                <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="600" style="max-width: 600px; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); overflow: hidden;">
                    <!-- Header -->
                    <tr>
                        <td style="background: linear-gradient(135deg, #1c3c4a 0%%, #2d5a6f 100%%); padding: 40px 40px 30px; text-align: center;">
                            <h1 style="margin: 0; color: #ffffff; font-size: 28px; font-weight: 600; letter-spacing: -0.5px;">Password Reset Request</h1>
                        </td>
                    </tr>
                    
                    <!-- Content -->
                    <tr>
                        <td style="padding: 40px 40px 30px;">
                            <p style="margin: 0 0 20px; color: #333333; font-size: 16px; line-height: 1.6;">Hello,</p>
                            <p style="margin: 0 0 30px; color: #555555; font-size: 15px; line-height: 1.6;">You have requested to reset your password. Please use the verification code below to complete the process:</p>
                            
                            <!-- OTP Code Box -->
                            <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%%">
                                <tr>
                                    <td align="center" style="padding: 0 0 30px;">
                                        <div style="background: linear-gradient(135deg, #f8f9fa 0%%, #e9ecef 100%%); border: 2px dashed #1c3c4a; border-radius: 12px; padding: 30px 40px; display: inline-block;">
                                            <div style="font-size: 36px; font-weight: 700; letter-spacing: 8px; color: #1c3c4a; font-family: 'Courier New', monospace; text-align: center; line-height: 1.2;">%s</div>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                            
                            <!-- Important Notice -->
                            <div style="background-color: #fff3cd; border-left: 4px solid #ffc107; padding: 15px 20px; margin: 0 0 30px; border-radius: 4px;">
                                <p style="margin: 0; color: #856404; font-size: 14px; line-height: 1.5;">
                                    <strong style="display: block; margin-bottom: 5px;">⚠️ Important:</strong>
                                    This verification code will expire in <strong>10 minutes</strong>. For security reasons, please do not share this code with anyone.
                                </p>
                            </div>
                            
                            <p style="margin: 0 0 20px; color: #555555; font-size: 15px; line-height: 1.6;">If you did not request this password reset, please ignore this email or contact our support team if you have concerns.</p>
                            
                            <p style="margin: 0; color: #333333; font-size: 16px; line-height: 1.6;">
                                Best regards,<br>
                                <strong style="color: #1c3c4a;">%s Team</strong>
                            </p>
                        </td>
                    </tr>
                    
                    <!-- Footer -->
                    <tr>
                        <td style="background-color: #f8f9fa; padding: 30px 40px; border-top: 1px solid #e9ecef;">
                            <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%%">
                                <tr>
                                    <td style="text-align: center; padding: 0 0 15px;">
                                        <p style="margin: 0; color: #6c757d; font-size: 13px; line-height: 1.5;">
                                            This is an automated message. Please do not reply to this email.
                                        </p>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="text-align: center; padding: 15px 0 0; border-top: 1px solid #e9ecef;">
                                        <p style="margin: 0; color: #adb5bd; font-size: 12px; line-height: 1.4;">
                                            © %s %s. All rights reserved.<br>
                                            <span style="color: #6c757d;">Need help? Contact our support team.</span>
                                        </p>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                </table>
                
                <!-- Spacer -->
                <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="600" style="max-width: 600px;">
                    <tr>
                        <td style="padding: 20px 0; text-align: center;">
                            <p style="margin: 0; color: #adb5bd; font-size: 11px; line-height: 1.4;">
                                This email was sent to <strong style="color: #6c757d;">%s</strong><br>
                                If you have any questions, please contact our support team.
                            </p>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>`, otp, s.fromName, "2026", s.fromName, email)

	// Build email message
	msg := []byte(fmt.Sprintf("From: %s <%s>\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n%s",
		s.fromName, s.fromEmail, email, subject, htmlBody))

	// Send email based on port
	to := []string{email}
	addr := fmt.Sprintf("%s:%d", s.smtpHost, port)

	log.Printf("SendOTP: Sending email to %s via %s (port %d)", email, addr, port)

	// Port 465 requires SSL/TLS from the start
	if port == 465 {
		err = s.sendWithSSL(addr, auth, s.fromEmail, to, msg)
	} else {
		// Port 587 uses STARTTLS
		err = smtp.SendMail(addr, auth, s.fromEmail, to, msg)
	}

	if err != nil {
		log.Printf("SendOTP: Failed to send email to %s: %v", email, err)
		return fmt.Errorf("failed to send email: %w", err)
	}

	log.Printf("SendOTP: Email sent successfully to %s", email)
	return nil
}

// sendWithSSL sends email using SSL/TLS connection (for port 465)
func (s *EmailService) sendWithSSL(addr string, auth smtp.Auth, from string, to []string, msg []byte) error {
	// Connect to SMTP server
	conn, err := tls.Dial("tcp", addr, &tls.Config{
		ServerName:         s.smtpHost,
		InsecureSkipVerify: false, // Set to true only for testing with self-signed certs
	})
	if err != nil {
		return fmt.Errorf("failed to connect to SMTP server: %w", err)
	}
	defer conn.Close()

	// Create SMTP client
	client, err := smtp.NewClient(conn, s.smtpHost)
	if err != nil {
		return fmt.Errorf("failed to create SMTP client: %w", err)
	}
	defer client.Close()

	// Authenticate
	if err = client.Auth(auth); err != nil {
		return fmt.Errorf("failed to authenticate: %w", err)
	}

	// Set sender
	if err = client.Mail(from); err != nil {
		return fmt.Errorf("failed to set sender: %w", err)
	}

	// Set recipients
	for _, recipient := range to {
		if err = client.Rcpt(recipient); err != nil {
			return fmt.Errorf("failed to set recipient %s: %w", recipient, err)
		}
	}

	// Send email body
	writer, err := client.Data()
	if err != nil {
		return fmt.Errorf("failed to get data writer: %w", err)
	}

	if _, err = writer.Write(msg); err != nil {
		return fmt.Errorf("failed to write message: %w", err)
	}

	if err = writer.Close(); err != nil {
		return fmt.Errorf("failed to close writer: %w", err)
	}

	// Quit
	if err = client.Quit(); err != nil {
		return fmt.Errorf("failed to quit: %w", err)
	}

	return nil
}
