import { query } from './db';
import { generateClickRef } from './tracking';

const RESEND_API_KEY = process.env.RESEND_API_KEY || import.meta.env?.RESEND_API_KEY || '';
const BASE_URL = process.env.SITE_URL || import.meta.env?.SITE_URL || 'https://sneakerpicks.nl';
const FROM_EMAIL = 'SneakerPicks <alerts@sneakerpicks.nl>';

interface ResendResponse {
  id?: string;
  error?: { message: string };
}

async function sendEmail(to: string, subject: string, html: string): Promise<ResendResponse> {
  if (!RESEND_API_KEY) {
    console.error('RESEND_API_KEY not set');
    return { error: { message: 'RESEND_API_KEY not configured' } };
  }
  const res = await fetch('https://api.resend.com/emails', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${RESEND_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ from: FROM_EMAIL, to: [to], subject, html }),
  });
  return res.json();
}

export async function sendVerificationEmail(email: string, token: string): Promise<ResendResponse> {
  const verifyUrl = `${BASE_URL}/api/auth/verify?token=${token}`;
  const html = emailLayout('Bevestig je email', `
    <h2 style="color:#fff;margin:0 0 16px">Welkom bij SneakerPicks! 👟</h2>
    <p style="color:#aaa;margin:0 0 24px">Klik op de knop hieronder om je email te bevestigen en je watchlist te activeren.</p>
    ${buttonHtml(verifyUrl, 'Email bevestigen')}
    <p style="color:#666;font-size:12px;margin-top:24px">Of kopieer deze link: ${verifyUrl}</p>
  `);
  return sendEmail(email, 'Bevestig je email - SneakerPicks', html);
}

export async function sendMagicLinkEmail(email: string, token: string): Promise<ResendResponse> {
  const loginUrl = `${BASE_URL}/api/auth/verify?token=${token}&login=1`;
  const html = emailLayout('Inloggen bij SneakerPicks', `
    <h2 style="color:#fff;margin:0 0 16px">Log in bij SneakerPicks 🔑</h2>
    <p style="color:#aaa;margin:0 0 24px">Klik op de knop hieronder om in te loggen. Deze link is 1 uur geldig.</p>
    ${buttonHtml(loginUrl, 'Inloggen')}
    <p style="color:#666;font-size:12px;margin-top:24px">Of kopieer deze link: ${loginUrl}</p>
  `);
  return sendEmail(email, 'Inloglink - SneakerPicks', html);
}

interface OfferForEmail {
  shop_name: string;
  price: number;
  affiliate_url: string;
  feed_id: number;
}

interface ProductForEmail {
  id: number;
  name: string;
  brand: string;
  image_url: string;
  cutout_image_url?: string;
}

export async function sendPriceAlertEmail(
  userId: string,
  userEmail: string,
  product: ProductForEmail,
  offers: OfferForEmail[],
  targetPrice: number
): Promise<ResendResponse> {
  const lowestPrice = Math.min(...offers.map(o => o.price));
  const imageUrl = product.cutout_image_url || product.image_url;

  let offerRows = '';
  for (const offer of offers.sort((a, b) => a.price - b.price)) {
    const clickRef = generateClickRef();
    // Store click event for email tracking
    try {
      // click_events expects UUID product_id but products use integer IDs
      // Skip tracking insert for email clicks — tracked via email_log instead
    } catch (e) { /* click_events schema mismatch */ }

    const url = appendClickRef(offer.affiliate_url, clickRef);
    offerRows += `
      <tr>
        <td style="padding:8px 0;color:#fff">${offer.shop_name}</td>
        <td style="padding:8px 0;text-align:right">
          <a href="${url}" style="display:inline-block;background:#00FF6A;color:#000;padding:8px 16px;border-radius:8px;text-decoration:none;font-weight:bold;font-size:14px">
            €${offer.price.toFixed(2).replace('.', ',')}
          </a>
        </td>
      </tr>`;
  }

  const html = emailLayout('Prijsalert! 🔥', `
    <div style="text-align:center;margin-bottom:24px">
      <img src="${imageUrl}" alt="${product.brand} ${product.name}" style="max-width:200px;max-height:200px" />
    </div>
    <h2 style="color:#fff;margin:0 0 8px">${product.brand} ${product.name}</h2>
    <p style="color:#00FF6A;font-size:20px;font-weight:bold;margin:0 0 4px">Vanaf €${lowestPrice.toFixed(2).replace('.', ',')}</p>
    <p style="color:#aaa;margin:0 0 24px">Onder je target van €${targetPrice.toFixed(2).replace('.', ',')} 🎯</p>
    <table style="width:100%;border-collapse:collapse">${offerRows}</table>
  `, userId);

  const result = await sendEmail(userEmail, `💰 Prijsdaling: ${product.brand} ${product.name} - vanaf €${lowestPrice.toFixed(2).replace('.', ',')}`, html);
  
  if (result.id) {
    await query(
      'INSERT INTO email_log (user_id, email_type, product_id, resend_id) VALUES ($1, $2, $3, $4)',
      [userId, 'price_alert', product.id, result.id]
    );
  }
  return result;
}

interface WatchlistDigestItem {
  product_id: number;
  name: string;
  brand: string;
  image_url: string;
  cutout_image_url?: string;
  current_price: number;
  price_7d_ago?: number;
  offers: OfferForEmail[];
}

export async function sendWeeklyWatchlistDigest(
  userId: string,
  userEmail: string,
  items: WatchlistDigestItem[]
): Promise<ResendResponse> {
  // Sort by biggest price drop first
  const sorted = [...items].sort((a, b) => {
    const dropA = a.price_7d_ago ? ((a.price_7d_ago - a.current_price) / a.price_7d_ago) : 0;
    const dropB = b.price_7d_ago ? ((b.price_7d_ago - b.current_price) / b.price_7d_ago) : 0;
    return dropB - dropA;
  });

  let productBlocks = '';
  for (const item of sorted) {
    const img = item.cutout_image_url || item.image_url;
    let priceChange = '';
    if (item.price_7d_ago && item.price_7d_ago !== item.current_price) {
      const diff = item.current_price - item.price_7d_ago;
      const color = diff < 0 ? '#00FF6A' : '#ff4444';
      const arrow = diff < 0 ? '↓' : '↑';
      priceChange = `<span style="color:${color};font-size:12px;margin-left:8px">${arrow} €${Math.abs(diff).toFixed(2).replace('.', ',')}</span>`;
    }

    // Best offer link
    const bestOffer = item.offers.sort((a, b) => a.price - b.price)[0];
    let bestLink = '#';
    if (bestOffer) {
      const clickRef = generateClickRef();
      try {
        // click_events expects UUID product_id but products use integer IDs
        // Skip tracking insert for digest clicks — tracked via email_log instead
      } catch (e) {}
      bestLink = appendClickRef(bestOffer.affiliate_url, clickRef);
    }

    productBlocks += `
      <div style="display:flex;gap:16px;padding:16px 0;border-bottom:1px solid #333">
        <img src="${img}" alt="${item.brand} ${item.name}" style="width:80px;height:80px;object-fit:contain" />
        <div style="flex:1">
          <p style="color:#888;font-size:11px;text-transform:uppercase;margin:0">${item.brand}</p>
          <p style="color:#fff;font-weight:bold;margin:4px 0">${item.name}</p>
          <p style="margin:4px 0">
            <span style="color:#00FF6A;font-weight:bold">€${item.current_price.toFixed(2).replace('.', ',')}</span>
            ${priceChange}
          </p>
          <a href="${bestLink}" style="color:#00FF6A;font-size:13px;text-decoration:none">Bekijk beste deal →</a>
        </div>
      </div>`;
  }

  const html = emailLayout('Je Watchlist Update 👀', `
    <h2 style="color:#fff;margin:0 0 8px">Je wekelijkse watchlist update</h2>
    <p style="color:#aaa;margin:0 0 24px">${items.length} sneaker${items.length !== 1 ? 's' : ''} op je watchlist</p>
    ${productBlocks}
    <div style="text-align:center;margin-top:24px">
      ${buttonHtml(`${BASE_URL}/watchlist`, 'Bekijk je volledige watchlist')}
    </div>
  `, userId);

  const result = await sendEmail(userEmail, `👀 Watchlist update: ${items.length} sneakers`, html);
  if (result.id) {
    await query(
      'INSERT INTO email_log (user_id, email_type, resend_id) VALUES ($1, $2, $3)',
      [userId, 'weekly_watchlist', result.id]
    );
  }
  return result;
}

function appendClickRef(url: string, clickRef: string): string {
  try {
    const u = new URL(url);
    u.searchParams.set('clickRef', clickRef);
    return u.toString();
  } catch {
    return url + (url.includes('?') ? '&' : '?') + `clickRef=${clickRef}`;
  }
}

function buttonHtml(url: string, text: string): string {
  return `<a href="${url}" style="display:inline-block;background:#00FF6A;color:#000;padding:12px 32px;border-radius:12px;text-decoration:none;font-weight:bold;font-size:16px">${text}</a>`;
}

function emailLayout(title: string, body: string, userId?: string): string {
  const unsubLink = userId ? `<p style="text-align:center;margin-top:32px"><a href="${BASE_URL}/api/auth/unsubscribe?uid=${userId}" style="color:#666;font-size:12px;text-decoration:underline">Uitschrijven</a></p>` : '';
  return `<!DOCTYPE html><html><head><meta charset="utf-8"></head>
<body style="margin:0;padding:0;background:#0a0a0a;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif">
  <div style="max-width:560px;margin:0 auto;padding:32px 16px">
    <div style="text-align:center;margin-bottom:24px">
      <span style="font-size:24px;font-weight:900;color:#fff">Sneaker</span><span style="font-size:24px;font-weight:900;color:#00FF6A">Picks</span>
    </div>
    <div style="background:#141414;border-radius:16px;padding:24px;border:1px solid #222">
      ${body}
    </div>
    ${unsubLink}
    <p style="text-align:center;color:#444;font-size:11px;margin-top:16px">© ${new Date().getFullYear()} SneakerPicks.nl</p>
  </div>
</body></html>`;
}
