import type { Express } from "express";
import { createServer, type Server } from "http";
import { z } from "zod";
import { storage } from "./storage";
import { leadSubmissionSchema } from "@shared/schema";
import nodemailer from "nodemailer";

// Email configuration
const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST || "smtp.gmail.com",
  port: parseInt(process.env.SMTP_PORT || "587"),
  secure: false,
  auth: {
    user: process.env.SMTP_USER || process.env.EMAIL_USER,
    pass: process.env.SMTP_PASS || process.env.EMAIL_PASS,
  },
});

// PerfexCRM integration
async function submitToPerfexCRM(leadData: any) {
  const perfexUrl = process.env.PERFEX_URL;
  const perfexToken = process.env.PERFEX_TOKEN;
  
  if (!perfexUrl || !perfexToken) {
    console.warn("PerfexCRM credentials not configured");
    return;
  }

  try {
    const response = await fetch(`${perfexUrl}/api/leads`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authtoken": perfexToken,
      },
      body: JSON.stringify({
        name: leadData.name,
        email: leadData.email,
        phone: leadData.phone,
        company: leadData.company,
        source: "1", // Green Tech Widget source
        status: "1", // New lead status
        assigned: "1", // Default assignment
        description: `
Service Type: ${leadData.serviceType}
Volume: ${leadData.totalBoxes} boxes (${leadData.totalWeight} lbs)
Timeline: ${leadData.timeline}
Location: ${leadData.zipCode}
Material Types: ${leadData.materialTypes.join(", ")}
Special Requirements: ${leadData.specialRequirements.join(", ")}
Quote Amount: $${leadData.quoteAmount}
        `.trim(),
      }),
    });

    if (!response.ok) {
      throw new Error(`PerfexCRM API error: ${response.statusText}`);
    }

    console.log("Lead successfully submitted to PerfexCRM");
  } catch (error) {
    console.error("Failed to submit to PerfexCRM:", error);
  }
}

// Email notification
async function sendEmailNotification(leadData: any) {
  try {
    await transporter.sendMail({
      from: process.env.SMTP_USER || "noreply@greentechshredding.com",
      to: "cnngraphics@gmail.com",
      subject: `New Shredding Lead - ${leadData.name}`,
      html: `
        <h2>New Lead from Green Tech Shredding Widget</h2>
        <div style="font-family: Arial, sans-serif; line-height: 1.6;">
          <h3>Contact Information</h3>
          <p><strong>Name:</strong> ${leadData.name}</p>
          <p><strong>Email:</strong> ${leadData.email}</p>
          <p><strong>Phone:</strong> ${leadData.phone}</p>
          <p><strong>Company:</strong> ${leadData.company || "N/A"}</p>
          <p><strong>Preferred Contact:</strong> ${leadData.preferredContact}</p>
          
          <h3>Service Details</h3>
          <p><strong>Service Type:</strong> ${leadData.serviceType}</p>
          <p><strong>Volume:</strong> ${leadData.totalBoxes} boxes (${leadData.totalWeight} lbs)</p>
          <p><strong>Timeline:</strong> ${leadData.timeline}</p>
          <p><strong>Location:</strong> ${leadData.zipCode}</p>
          <p><strong>Quote Amount:</strong> $${leadData.quoteAmount}</p>
          
          <h3>Material Types</h3>
          <p>${leadData.materialTypes.join(", ")}</p>
          
          <h3>Special Requirements</h3>
          <p>${leadData.specialRequirements.length > 0 ? leadData.specialRequirements.join(", ") : "None"}</p>
          
          <h3>Volume Breakdown</h3>
          <ul>
            <li>File Boxes: ${leadData.volumeData.fileBoxes}</li>
            <li>Filing Cabinets: ${leadData.volumeData.filingCabinets}</li>
            <li>Bags: ${leadData.volumeData.bags}</li>
            <li>Pallets: ${leadData.volumeData.pallets}</li>
          </ul>
        </div>
      `,
    });

    // Send confirmation email to customer
    await transporter.sendMail({
      from: process.env.SMTP_USER || "noreply@greentechshredding.com",
      to: leadData.email,
      subject: "Your Green Tech Shredding Quote",
      html: `
        <h2>Thank you for your shredding quote request!</h2>
        <div style="font-family: Arial, sans-serif; line-height: 1.6;">
          <p>Dear ${leadData.name},</p>
          
          <p>Thank you for requesting a quote from Green Tech Shredding. We've received your information and will contact you within 24 hours to schedule your service.</p>
          
          <div style="background-color: #f0fdf4; padding: 20px; border-radius: 8px; margin: 20px 0;">
            <h3 style="color: #065f46; margin-top: 0;">Your Quote Summary</h3>
            <p><strong>Service Type:</strong> ${leadData.serviceType}</p>
            <p><strong>Volume:</strong> ${leadData.totalBoxes} boxes (${leadData.totalWeight} lbs)</p>
            <p><strong>Estimated Price:</strong> $${leadData.quoteAmount}</p>
            <p><strong>Timeline:</strong> ${leadData.timeline}</p>
          </div>
          
          <p>Our team will reach out to you via ${leadData.preferredContact} to confirm the details and schedule your secure document destruction service.</p>
          
          <p>If you have any immediate questions, please don't hesitate to call us at <strong>(800) 555-SHRED</strong>.</p>
          
          <p>Best regards,<br>The Green Tech Shredding Team</p>
        </div>
      `,
    });

    console.log("Email notifications sent successfully");
  } catch (error) {
    console.error("Failed to send email notification:", error);
  }
}

export async function registerRoutes(app: Express): Promise<Server> {
  // Submit lead
  app.post("/api/leads", async (req, res) => {
    try {
      const leadData = leadSubmissionSchema.parse(req.body);
      
      // Create lead in storage
      const lead = await storage.createLead(leadData);
      
      // Submit to PerfexCRM (async, don't block response)
      submitToPerfexCRM(leadData).catch(console.error);
      
      // Send email notifications (async, don't block response)
      sendEmailNotification(leadData).catch(console.error);
      
      res.json({ 
        success: true, 
        leadId: lead.id,
        message: "Lead submitted successfully" 
      });
    } catch (error) {
      console.error("Lead submission error:", error);
      if (error instanceof z.ZodError) {
        res.status(400).json({ 
          success: false, 
          error: "Validation error", 
          details: error.errors 
        });
      } else {
        res.status(500).json({ 
          success: false, 
          error: "Internal server error" 
        });
      }
    }
  });

  // Get all leads (for admin)
  app.get("/api/leads", async (req, res) => {
    try {
      const leads = await storage.getLeads();
      res.json({ leads });
    } catch (error) {
      console.error("Failed to fetch leads:", error);
      res.status(500).json({ error: "Failed to fetch leads" });
    }
  });

  // Get widget embed code
  app.get("/api/widget/embed", (req, res) => {
    const baseUrl = req.get('host');
    const protocol = req.get('x-forwarded-proto') || req.protocol;
    
    const iframeCode = `<iframe src="${protocol}://${baseUrl}/widget" width="100%" height="800" frameborder="0" style="border-radius: 12px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);"></iframe>`;
    
    const scriptCode = `<div id="greentech-widget"></div>
<script>
(function() {
  var iframe = document.createElement('iframe');
  iframe.src = '${protocol}://${baseUrl}/widget';
  iframe.width = '100%';
  iframe.height = '800';
  iframe.frameBorder = '0';
  iframe.style.borderRadius = '12px';
  iframe.style.boxShadow = '0 4px 6px -1px rgba(0, 0, 0, 0.1)';
  document.getElementById('greentech-widget').appendChild(iframe);
})();
</script>`;

    res.json({
      iframe: iframeCode,
      script: scriptCode
    });
  });

  const httpServer = createServer(app);
  return httpServer;
}
