
// Email notification system
// import { Quote, Lead, Contract, User } from '@prisma/client';
type Contract = any;
type User = any;
type Lead = any;
type Quote = any;

export interface EmailTemplate {
  subject: string;
  html: string;
  text: string;
}

export interface EmailOptions {
  to: string;
  subject: string;
  html: string;
  text?: string;
}

export async function sendEmail(
  to: string,
  template: EmailTemplate
): Promise<boolean>;
export async function sendEmail(options: EmailOptions): Promise<boolean>;
export async function sendEmail(
  toOrOptions: string | EmailOptions,
  template?: EmailTemplate
): Promise<boolean> {
  try {
    let to: string;
    let subject: string;
    let html: string;
    let text: string;

    if (typeof toOrOptions === 'string' && template) {
      to = toOrOptions;
      subject = template.subject;
      html = template.html;
      text = template.text;
    } else if (typeof toOrOptions === 'object') {
      to = toOrOptions.to;
      subject = toOrOptions.subject;
      html = toOrOptions.html;
      text = toOrOptions.text || '';
    } else {
      throw new Error('Invalid email parameters');
    }

    // Use SendGrid for production email sending
    if (process.env.SENDGRID_API_KEY) {
      try {
        const sgMail = require('@sendgrid/mail');
        sgMail.setApiKey(process.env.SENDGRID_API_KEY);
        
        await sgMail.send({
          to,
          from: process.env.SMTP_FROM || 'noreply@quote2contract.com',
          subject,
          html,
          text: text || html.replace(/<[^>]*>/g, ''), // Strip HTML if no text version
        });
        
        console.log('✅ Email sent successfully to:', to);
        return true;
      } catch (sgError: any) {
        console.error('SendGrid error:', sgError.response?.body || sgError);
        // Fallback to console logging if SendGrid fails
        console.log('📧 Email (fallback) to:', to);
        console.log('Subject:', subject);
        return false;
      }
    } else {
      // Development mode: log emails to console
      console.log('📧 Email (dev mode) to:', to);
      console.log('Subject:', subject);
      console.log('Content preview:', (text || html).substring(0, 200));
      return true;
    }
  } catch (error) {
    console.error('Failed to send email:', error);
    return false;
  }
}

// Email templates
export const emailTemplates = {
  quoteCreated: (quote: Quote, customer: any): EmailTemplate => ({
    subject: `New Quote #${quote.quoteNumber} Created`,
    html: `
      <h1>Your Quote is Ready!</h1>
      <p>Dear ${customer.name},</p>
      <p>We've created a quote for your ${quote.services.join(', ')} project.</p>
      <p><strong>Quote Details:</strong></p>
      <ul>
        <li>Quote Number: #${quote.quoteNumber}</li>
        <li>Services: ${quote.services.join(', ')}</li>
        <li>Total: $${quote.total.toFixed(2)}</li>
      </ul>
      <p>You can view and accept your quote by logging into your customer portal.</p>
      <p>Best regards,<br>Quote2Contract Team</p>
    `,
    text: `Your Quote is Ready! Quote #${quote.quoteNumber} for ${quote.services.join(', ')} - Total: $${quote.total.toFixed(2)}`,
  }),

  leadReceived: (lead: Lead): EmailTemplate => ({
    subject: `New Lead from ${lead.firstName} ${lead.lastName}`,
    html: `
      <h1>New Lead Received</h1>
      <p><strong>Lead Details:</strong></p>
      <ul>
        <li>Name: ${lead.firstName} ${lead.lastName}</li>
        <li>Email: ${lead.email}</li>
        <li>Phone: ${lead.phone || 'Not provided'}</li>
        <li>Services: ${lead.services.join(', ')}</li>
        <li>Status: ${lead.status}</li>
      </ul>
      <p>Description: ${lead.description || 'No description provided'}</p>
    `,
    text: `New lead from ${lead.firstName} ${lead.lastName} - ${lead.services.join(', ')}`,
  }),

  contractGenerated: (contract: Contract, customer: any): EmailTemplate => ({
    subject: `Contract Ready for Signature - #${contract.id}`,
    html: `
      <h1>Contract Ready for Your Signature</h1>
      <p>Dear ${customer.name},</p>
      <p>Your contract is ready for review and signature.</p>
      <p><strong>Contract Details:</strong></p>
      <ul>
        <li>Contract ID: #${contract.id}</li>
        <li>Status: ${contract.status}</li>
      </ul>
      <p>Please log in to your customer portal to review and sign the contract.</p>
      <p>Best regards,<br>Quote2Contract Team</p>
    `,
    text: `Contract #${contract.id} is ready for your signature`,
  }),

  contractSigned: (contract: Contract): EmailTemplate => ({
    subject: `Contract Signed - #${contract.id}`,
    html: `
      <h1>Contract Successfully Signed</h1>
      <p>Contract #${contract.id} has been signed by all parties.</p>
      <p>Work can now begin on this project.</p>
      <p>Best regards,<br>Quote2Contract Team</p>
    `,
    text: `Contract #${contract.id} has been signed`,
  }),

  welcomeEmail: (user: User): EmailTemplate => ({
    subject: 'Welcome to Quote2Contract CRM',
    html: `
      <h1>Welcome to Quote2Contract!</h1>
      <p>Hi ${user.name || 'there'},</p>
      <p>Thank you for signing up for Quote2Contract CRM.</p>
      <p>You can now:</p>
      <ul>
        <li>Create and manage quotes</li>
        <li>Track leads and conversions</li>
        <li>Generate contracts with e-signatures</li>
        <li>Sync your calendar</li>
        <li>And much more!</li>
      </ul>
      <p>Get started by logging in to your dashboard.</p>
      <p>Best regards,<br>Quote2Contract Team</p>
    `,
    text: `Welcome to Quote2Contract CRM! Start managing your home services business today.`,
  }),
};

// Helper functions for lead emails
export function getCustomerConfirmationEmail(customerName: string, serviceType: string): string {
  return `
    <!DOCTYPE html>
    <html>
      <head>
        <style>
          body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
          .container { max-width: 600px; margin: 0 auto; padding: 20px; }
          .header { background-color: #6dbf4d; color: white; padding: 20px; text-align: center; }
          .content { background-color: #f9f9f9; padding: 30px; }
          .button { background-color: #6dbf4d; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; display: inline-block; margin: 20px 0; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>Quote Request Received ✓</h1>
          </div>
          <div class="content">
            <p>Dear ${customerName},</p>
            <p>Thank you for your interest in our ${serviceType} services!</p>
            <p>We have received your quote request and our team is currently reviewing it. You can expect to hear from us within 24-48 hours with a detailed quote.</p>
            <p><strong>What happens next?</strong></p>
            <ol>
              <li>Our team reviews your project details</li>
              <li>We prepare a customized quote</li>
              <li>You receive your quote via email</li>
              <li>You can accept, discuss, or request changes</li>
            </ol>
            <p>If you have any questions in the meantime, please don't hesitate to reach out.</p>
            <p>Best regards,<br><strong>Quote2Contract Team</strong></p>
          </div>
        </div>
      </body>
    </html>
  `;
}

export function getCrmNotificationEmail(data: {
  name: string;
  email: string;
  phone?: string;
  serviceType: string;
  address?: string;
  leadId: string;
}): string {
  return `
    <!DOCTYPE html>
    <html>
      <head>
        <style>
          body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
          .container { max-width: 600px; margin: 0 auto; padding: 20px; }
          .header { background-color: #03496c; color: white; padding: 20px; text-align: center; }
          .content { background-color: #f9f9f9; padding: 30px; }
          .info-box { background-color: white; border-left: 4px solid #6dbf4d; padding: 15px; margin: 15px 0; }
          .label { font-weight: bold; color: #03496c; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>🚨 New Quote Request</h1>
          </div>
          <div class="content">
            <p><strong>Action Required:</strong> A new quote request has been submitted and needs your attention.</p>
            
            <div class="info-box">
              <p><span class="label">Lead ID:</span> ${data.leadId}</p>
              <p><span class="label">Customer Name:</span> ${data.name}</p>
              <p><span class="label">Email:</span> ${data.email}</p>
              ${data.phone ? `<p><span class="label">Phone:</span> ${data.phone}</p>` : ''}
              <p><span class="label">Service Type:</span> ${data.serviceType}</p>
              ${data.address ? `<p><span class="label">Address:</span> ${data.address}</p>` : ''}
            </div>
            
            <p>Please log in to the CRM to review the full details and generate a quote.</p>
            
            <p><strong>Next Steps:</strong></p>
            <ol>
              <li>Review the lead details in the CRM</li>
              <li>Contact the customer if more information is needed</li>
              <li>Prepare and send a quote</li>
            </ol>
          </div>
        </div>
      </body>
    </html>
  `;
}
