import type { SellerLead, Buyer } from "@/types";

// ============================================
// EMAIL GENERATION
// ============================================

export function generateDealEmail(
  lead: SellerLead,
  buyer: Buyer,
  agentName: string,
  agentCompany?: string
): { subject: string; body: string; html: string } {
  const subject = `New ${lead.asset_type} Opportunity — ${lead.market}`;

  const priceFormatted = new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: 0,
  }).format(lead.asking_price);

  const sqftFormatted = lead.sqft
    ? new Intl.NumberFormat("en-US").format(lead.sqft) + " SF"
    : "N/A";

  const body = `Hi ${buyer.name},

I have a new ${lead.asset_type.toLowerCase()} opportunity that matches your acquisition criteria and wanted to get it in front of you early.

Property Highlights:
• Asset Type: ${lead.asset_type}
• Location: ${lead.address}, ${lead.market}
• Asking Price: ${priceFormatted}
• Cap Rate: ${lead.cap_rate ? lead.cap_rate.toFixed(2) + "%" : "TBD"}
• NOI: ${lead.noi ? "$" + new Intl.NumberFormat("en-US").format(lead.noi) : "Available upon request"}
• Size: ${sqftFormatted}${lead.units ? " | " + lead.units + " units" : ""}
${lead.year_built ? "• Year Built: " + lead.year_built : ""}

This is an off-market opportunity with limited distribution. If you'd like to receive the full offering memorandum, please reply to this email or sign the confidentiality agreement through our portal.

Best regards,
${agentName}${agentCompany ? "\n" + agentCompany : ""}

---
Sent via CREdispo | Manage preferences: {{unsubscribe_link}}`;

  const html = `
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; color: #1a2847; line-height: 1.6; }
    .container { max-width: 600px; margin: 0 auto; padding: 20px; }
    .header { background: linear-gradient(135deg, #1a2847 0%, #263c6b 100%); color: white; padding: 24px; border-radius: 8px 8px 0 0; }
    .header h1 { margin: 0; font-size: 20px; color: #fbbf24; }
    .header p { margin: 4px 0 0; opacity: 0.9; font-size: 14px; }
    .body { background: #ffffff; border: 1px solid #e5e7eb; border-top: none; padding: 24px; border-radius: 0 0 8px 8px; }
    .highlight-box { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; padding: 16px; margin: 16px 0; }
    .highlight-box table { width: 100%; border-collapse: collapse; }
    .highlight-box td { padding: 6px 0; font-size: 14px; }
    .highlight-box td:first-child { font-weight: 600; width: 120px; color: #64748b; }
    .cta { display: inline-block; background: #fbbf24; color: #1a2847; padding: 12px 24px; border-radius: 6px; text-decoration: none; font-weight: 600; margin: 16px 0; }
    .footer { text-align: center; padding: 16px; color: #94a3b8; font-size: 12px; }
    .footer a { color: #64748b; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>New Investment Opportunity</h1>
      <p>${lead.asset_type} — ${lead.market}</p>
    </div>
    <div class="body">
      <p>Hi ${buyer.name},</p>
      <p>I have a new ${lead.asset_type.toLowerCase()} opportunity that matches your acquisition criteria and wanted to get it in front of you early.</p>
      
      <div class="highlight-box">
        <table>
          <tr><td>Asset Type</td><td>${lead.asset_type}</td></tr>
          <tr><td>Location</td><td>${lead.address}, ${lead.market}</td></tr>
          <tr><td>Asking Price</td><td><strong>${priceFormatted}</strong></td></tr>
          <tr><td>Cap Rate</td><td>${lead.cap_rate ? lead.cap_rate.toFixed(2) + "%" : "TBD"}</td></tr>
          <tr><td>NOI</td><td>${lead.noi ? "$" + new Intl.NumberFormat("en-US").format(lead.noi) : "Upon request"}</td></tr>
          <tr><td>Size</td><td>${sqftFormatted}${lead.units ? " | " + lead.units + " units" : ""}</td></tr>
          ${lead.year_built ? `<tr><td>Year Built</td><td>${lead.year_built}</td></tr>` : ""}
        </table>
      </div>

      <p>This is an <strong>off-market opportunity</strong> with limited distribution.</p>
      
      <a href="{{portal_link}}" class="cta">View Deal & Sign NDA →</a>
      
      <p>If you'd like to receive the full offering memorandum, please reply to this email or sign the confidentiality agreement through our portal.</p>
      
      <p>Best regards,<br><strong>${agentName}</strong>${agentCompany ? "<br>" + agentCompany : ""}</p>
    </div>
    <div class="footer">
      <p>Sent via CREdispo | <a href="{{unsubscribe_link}}">Manage preferences</a></p>
    </div>
  </div>
</body>
</html>`;

  return { subject, body, html };
}

// ============================================
// SMS GENERATION
// ============================================

export function generateDealSMS(
  lead: SellerLead,
  buyer: Buyer,
  agentName: string
): string {
  const priceFormatted =
    lead.asking_price >= 1000000
      ? "$" + (lead.asking_price / 1000000).toFixed(1) + "M"
      : "$" + (lead.asking_price / 1000).toFixed(0) + "K";

  return `${buyer.name.split(" ")[0]}, new ${lead.asset_type.toLowerCase()} opp in ${lead.market}: ${priceFormatted}, ${lead.cap_rate ? lead.cap_rate.toFixed(1) + "% cap" : "details avail"}. Reply YES for full info. - ${agentName} via CREdispo`;
}

// ============================================
// SEND EMAIL (Resend placeholder)
// ============================================

export async function sendEmail(
  to: string,
  subject: string,
  html: string,
  from?: string
): Promise<{ success: boolean; messageId?: string; error?: string }> {
  const apiKey = process.env.RESEND_API_KEY;
  const fromEmail = from || process.env.RESEND_FROM_EMAIL || "deals@credispo.com";

  if (!apiKey || apiKey === "re_...") {
    console.log("[EMAIL] Resend not configured. Would send to:", to);
    console.log("[EMAIL] Subject:", subject);
    return { success: true, messageId: "mock-" + Date.now() };
  }

  try {
    const response = await fetch("https://api.resend.com/emails", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        from: fromEmail,
        to,
        subject,
        html,
      }),
    });

    const data = await response.json();

    if (!response.ok) {
      return { success: false, error: data.message || "Failed to send email" };
    }

    return { success: true, messageId: data.id };
  } catch (error) {
    return { success: false, error: String(error) };
  }
}

// ============================================
// SEND SMS (Twilio placeholder)
// ============================================

export async function sendSMS(
  to: string,
  body: string
): Promise<{ success: boolean; messageId?: string; error?: string }> {
  const accountSid = process.env.TWILIO_ACCOUNT_SID;
  const authToken = process.env.TWILIO_AUTH_TOKEN;
  const fromNumber = process.env.TWILIO_PHONE_NUMBER;

  if (!accountSid || accountSid === "AC...") {
    console.log("[SMS] Twilio not configured. Would send to:", to);
    console.log("[SMS] Body:", body);
    return { success: true, messageId: "mock-sms-" + Date.now() };
  }

  try {
    const response = await fetch(
      `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Messages.json`,
      {
        method: "POST",
        headers: {
          Authorization: "Basic " + Buffer.from(`${accountSid}:${authToken}`).toString("base64"),
          "Content-Type": "application/x-www-form-urlencoded",
        },
        body: new URLSearchParams({
          To: to,
          From: fromNumber || "",
          Body: body,
        }),
      }
    );

    const data = await response.json();

    if (!response.ok) {
      return { success: false, error: data.message || "Failed to send SMS" };
    }

    return { success: true, messageId: data.sid };
  } catch (error) {
    return { success: false, error: String(error) };
  }
}
