package tender

import (
	"fmt"
	"html"
	"strings"
	"time"
)

// TenderConfirmationEmailTemplateData represents the data needed for the tender confirmation email template
type TenderConfirmationEmailTemplateData struct {
	TenderID          string
	TenderTitle       string
	TenderDescription string
	SubmittedBy       string
	CompanyName       string
	CompanyEmail      string
	SubmittedAt       int64
	EstimatedValue    string
	TenderDeadline    int64
	CompanyLogo       string
	CompanyURL        string
	SupportEmail      string
}

// GenerateTenderConfirmationEmailTemplate generates a beautiful HTML email template for tender submission confirmation
func GenerateTenderConfirmationEmailTemplate(data *TenderConfirmationEmailTemplateData) string {
	// Sanitize all user inputs before inserting into HTML
	safeTenderTitle := html.EscapeString(data.TenderTitle)
	safeTenderDescription := html.EscapeString(data.TenderDescription)
	safeSubmittedBy := html.EscapeString(data.SubmittedBy)
	safeCompanyName := html.EscapeString(data.CompanyName)
	safeCompanyEmail := html.EscapeString(data.CompanyEmail)

	// Format dates
	submittedAt := time.Unix(data.SubmittedAt, 0).Format("January 2, 2006 at 3:04 PM")
	deadlineAt := time.Unix(data.TenderDeadline, 0).Format("January 2, 2006")

	emailHTML := `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tender Submitted Successfully - {{COMPANY_NAME}}</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f8fafc;
        }
        
        .email-container {
            max-width: 700px;
            margin: 16px auto;
            background-color: #ffffff;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .header {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            padding: 40px 30px;
            text-align: center;
            color: white;
        }
        
        .logo {
            max-width: 200px;
            height: auto;
            margin-bottom: 20px;
            border-radius: 8px;
        }
        
        .header h1 {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .header p {
            font-size: 16px;
            opacity: 0.9;
            font-weight: 300;
        }
        
        .content {
            padding: 40px 30px;
        }
        
        .confirmation-card {
            background-color: #f0fdf4;
            border: 2px solid #10b981;
            border-radius: 12px;
            padding: 30px;
            margin: 30px 0;
            position: relative;
        }
        
        .confirmation-card::before {
            content: '✓';
            position: absolute;
            top: -15px;
            left: 20px;
            background-color: #10b981;
            color: white;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            font-weight: bold;
        }
        
        .success-message {
            color: #065f46;
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 20px;
            text-align: center;
        }
        
        .tender-details {
            background-color: white;
            border-radius: 8px;
            padding: 25px;
            margin: 20px 0;
            border-left: 4px solid #10b981;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }
        
        .detail-row {
            display: flex;
            margin-bottom: 15px;
            align-items: flex-start;
            padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .detail-row:last-child {
            border-bottom: none;
            margin-bottom: 0;
        }
        
        .detail-label {
            font-weight: 600;
            color: #374151;
            min-width: 140px;
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .detail-value {
            color: #6b7280;
            flex: 1;
            font-size: 14px;
        }
        
        .tender-title {
            font-size: 18px;
            font-weight: 600;
            color: #065f46;
            margin-bottom: 10px;
        }
        
        .tender-description {
            background-color: #f9fafb;
            border-radius: 6px;
            padding: 15px;
            margin-top: 10px;
            border-left: 3px solid #10b981;
            font-style: italic;
        }
        
        .value-proposition {
            background: linear-gradient(135deg, #ecfdf5, #d1fae5);
            border: 1px solid #a7f3d0;
            border-radius: 12px;
            padding: 25px;
            margin: 30px 0;
            text-align: center;
        }
        
        .value-proposition h3 {
            color: #065f46;
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 15px;
        }
        
        .value-proposition p {
            color: #047857;
            font-size: 15px;
            line-height: 1.6;
            margin-bottom: 10px;
        }
        
        .next-steps {
            background-color: #fefce8;
            border: 1px solid #fbbf24;
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
        }
        
        .next-steps h4 {
            color: #92400e;
            margin-bottom: 12px;
            font-size: 16px;
            font-weight: 600;
        }
        
        .next-steps ul {
            color: #78350f;
            padding-left: 20px;
        }
        
        .next-steps li {
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .timestamp {
            text-align: center;
            color: #6b7280;
            font-size: 14px;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e5e7eb;
        }
        
        .footer {
            background-color: #f8fafc;
            padding: 30px;
            text-align: center;
            border-top: 1px solid #e5e7eb;
        }
        
        .footer p {
            color: #6b7280;
            font-size: 14px;
            margin-bottom: 10px;
        }
        
        .footer a {
            color: #10b981;
            text-decoration: none;
        }
        
        .footer a:hover {
            text-decoration: underline;
        }
        
        .support-info {
            background-color: #ecfdf5;
            border: 1px solid #a7f3d0;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
        }
        
        .support-info h4 {
            color: #065f46;
            margin-bottom: 8px;
            font-size: 16px;
        }
        
        .support-info p {
            color: #047857;
            font-size: 14px;
            margin-bottom: 5px;
        }
        
        @media (max-width: 600px) {
            .email-container {
                margin: 16px;
                border-radius: 0;
            }
            .content {
                padding: 20px;
            }
            
            .detail-row {
                flex-direction: column;
                gap: 4px;
            }
            
            .header {
                padding: 30px 20px;
            }
            
            .header h1 {
                font-size: 24px;
            }
            
            .tender-details {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <!-- Header -->
        <div class="header">
            <h1>Tender Submitted Successfully!</h1>
            <p>Your tender has been received and is now under review</p>
        </div>
        
        <!-- Content -->
        <div class="content">
            <div class="confirmation-card">
                <div class="success-message">
                    ✓ Your tender submission has been confirmed!
                </div>
                
                <div class="tender-details">
                    <div class="tender-title">{{TENDER_TITLE}}</div>
                    
                    <div class="detail-row">
                        <span class="detail-label">Tender ID:</span>
                        <span class="detail-value">{{TENDER_ID}}</span>
                    </div>
                    
                    <div class="detail-row">
                        <span class="detail-label">Submitted By:</span>
                        <span class="detail-value">{{SUBMITTED_BY}}</span>
                    </div>
                    
                    <div class="detail-row">
                        <span class="detail-label">Company:</span>
                        <span class="detail-value">{{COMPANY_NAME}}</span>
                    </div>
                    
                    <div class="detail-row">
                        <span class="detail-label">Estimated Value:</span>
                        <span class="detail-value">{{ESTIMATED_VALUE}}</span>
                    </div>
                    
                    <div class="detail-row">
                        <span class="detail-label">Submission Deadline:</span>
                        <span class="detail-value">{{TENDER_DEADLINE}}</span>
                    </div>
                    
                    <div class="tender-description">
                        <strong>Description:</strong><br>
                        {{TENDER_DESCRIPTION}}
                    </div>
                </div>
                
                <div class="timestamp">
                    <strong>Submitted on:</strong> {{SUBMITTED_AT}}
                    <br>
                    <p>This email confirms your tender submission to {{COMPANY_NAME}}</p>
                </div>
            </div>
            
            <div class="value-proposition">
                <h3>🎯 What Happens Next?</h3>
                <p>Your tender is now in our review queue. Our procurement team will carefully evaluate your proposal against our requirements and selection criteria.</p>
                <p>You'll receive notifications at each stage of the process, keeping you informed and giving you the opportunity to provide additional information if needed.</p>
                <p><strong>Why choose us?</strong> We value transparency, fairness, and efficiency in our tender process, ensuring all qualified suppliers have an equal opportunity to contribute to our projects.</p>
            </div>
            
            <div class="next-steps">
                <h4>Next Steps & Timeline</h4>
                <ul>
                    <li><strong>Initial Review (1-2 business days):</strong> Our team will perform an initial assessment of your submission</li>
                    <li><strong>Detailed Evaluation (3-5 business days):</strong> Comprehensive review against our requirements</li>
                    <li><strong>Clarification Period (if needed):</strong> We'll contact you if we need additional information</li>
                    <li><strong>Final Decision:</strong> You'll be notified of the outcome within the tender timeline</li>
                </ul>
            </div>
            
            <div class="support-info">
                <h4>Need Help or Have Questions?</h4>
                <p><strong>Email:</strong> <a href="mailto:{{SUPPORT_EMAIL}}">{{SUPPORT_EMAIL}}</a></p>
                <p><strong>Portal:</strong> <a href="{{COMPANY_URL}}" target="_blank">{{COMPANY_URL}}</a></p>
                <p>Our team is here to support you throughout the tender process. Don't hesitate to reach out!</p>
            </div>
        </div>
        
        <!-- Footer -->
        <div class="footer">
            <p>This is an automated confirmation email from {{COMPANY_NAME}}</p>
            <p>Please save this email for your records. For questions, contact us at <a href="mailto:{{SUPPORT_EMAIL}}">{{SUPPORT_EMAIL}}</a></p>
        </div>
    </div>
</body>
</html>`

	// Replace placeholders with sanitized data
	emailHTML = strings.ReplaceAll(emailHTML, "{{COMPANY_NAME}}", safeCompanyName)
	emailHTML = strings.ReplaceAll(emailHTML, "{{TENDER_ID}}", html.EscapeString(data.TenderID))
	emailHTML = strings.ReplaceAll(emailHTML, "{{TENDER_TITLE}}", safeTenderTitle)
	emailHTML = strings.ReplaceAll(emailHTML, "{{TENDER_DESCRIPTION}}", safeTenderDescription)
	emailHTML = strings.ReplaceAll(emailHTML, "{{SUBMITTED_BY}}", safeSubmittedBy)
	emailHTML = strings.ReplaceAll(emailHTML, "{{COMPANY_EMAIL}}", safeCompanyEmail)
	emailHTML = strings.ReplaceAll(emailHTML, "{{SUBMITTED_AT}}", submittedAt)
	emailHTML = strings.ReplaceAll(emailHTML, "{{ESTIMATED_VALUE}}", html.EscapeString(data.EstimatedValue))
	emailHTML = strings.ReplaceAll(emailHTML, "{{TENDER_DEADLINE}}", deadlineAt)
	emailHTML = strings.ReplaceAll(emailHTML, "{{SUPPORT_EMAIL}}", html.EscapeString(data.SupportEmail))
	emailHTML = strings.ReplaceAll(emailHTML, "{{COMPANY_URL}}", html.EscapeString(data.CompanyURL))

	return emailHTML
}

// GenerateTenderConfirmationEmailMessage generates a simple text message for the email
func GenerateTenderConfirmationEmailMessage(data *TenderConfirmationEmailTemplateData) string {
	submittedAt := time.Unix(data.SubmittedAt, 0).Format("January 2, 2006 at 3:04 PM")
	deadlineAt := time.Unix(data.TenderDeadline, 0).Format("January 2, 2006")

	return fmt.Sprintf(`
Tender Submission Confirmation

✅ Your tender has been successfully submitted!

Tender Details:
- Tender ID: %s
- Title: %s
- Submitted By: %s
- Company: %s
- Estimated Value: %s
- Submission Deadline: %s
- Submitted on: %s

Description:
%s

🎯 What Happens Next?
Your tender is now under review by our procurement team. Here's what to expect:

1. Initial Review (1-2 business days): Preliminary assessment
2. Detailed Evaluation (3-5 business days): Comprehensive review
3. Clarification Period (if needed): We'll contact you for additional info
4. Final Decision: Notification of outcome within tender timeline

Why Choose Us?
• Transparent and fair evaluation process
• Equal opportunity for all qualified suppliers
• Dedicated support throughout the tender process
• Clear communication at every stage

Need Help?
Email: %s
Portal: %s

This is an automated confirmation from %s.
Please save this email for your records.

Best regards,
The Procurement Team
`,
		data.TenderID,
		data.TenderTitle,
		data.SubmittedBy,
		data.CompanyName,
		data.EstimatedValue,
		deadlineAt,
		submittedAt,
		data.TenderDescription,
		data.SupportEmail,
		data.CompanyURL,
		data.CompanyName,
	)
}

// GenerateTenderConfirmationEmailSubject generates an appropriate subject line for the email
func GenerateTenderConfirmationEmailSubject(data *TenderConfirmationEmailTemplateData) string {
	return fmt.Sprintf("✅ Tender Submitted: %s (ID: %s)", data.TenderTitle, data.TenderID)
}
