const express = require('express');
const jwt = require('jsonwebtoken');
const { MonthlyDraw, ChitGroup, User, GroupMember } = require('../models');

const router = express.Router();

function escapeHtml(str) {
  return String(str || '')
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#039;');
}

function formatInr(amount) {
  if (amount == null || amount === '') return '—';
  const n = Number(amount);
  if (Number.isNaN(n)) return escapeHtml(String(amount));
  try {
    return `₹${n.toLocaleString('en-IN', { maximumFractionDigits: 2 })}`;
  } catch {
    return `₹${n}`;
  }
}

/**
 * Render public draw page from signed JWT (same secret as POST /api/share/draw-link).
 * Token in query avoids ENAMETOOLONG / proxy issues from huge path segments.
 */
async function renderDrawSharePage(req, res, token) {
  const shareSecret = process.env.SHARE_TOKEN_SECRET || process.env.JWT_SECRET;
  if (!shareSecret) {
    return res.status(500).send('Share is not configured.');
  }

  let payload;
  try {
    payload = jwt.verify(token, shareSecret);
  } catch {
    return res.status(400).send('Invalid or expired share link.');
  }

  if (!payload?.type || payload.type !== 'draw_result' || !payload.drawId) {
    return res.status(400).send('Invalid share link.');
  }

  const draw = await MonthlyDraw.findByPk(payload.drawId, {
    include: [
      { model: ChitGroup, attributes: ['id', 'name'] },
      { model: User, as: 'winner', attributes: ['id', 'full_name', 'mobile_number'] }
    ]
  });

  if (!draw) {
    return res.status(404).send('Draw not found.');
  }

  const totalMembers = await GroupMember.count({
    where: { group_id: draw.group_id, status: 'active' }
  });

  const title = `Draw Result — ${draw.ChitGroup ? draw.ChitGroup.name : 'Chit Group'}`;
  const winnerName = draw.winner ? draw.winner.full_name : 'TBD';
  const groupName = draw.ChitGroup ? draw.ChitGroup.name : 'Chit Group';
  const subtitle = `${draw.month}/${draw.year} • Winner: ${winnerName}`;

  let drawWhen = '';
  try {
    const d = draw.draw_date ? new Date(draw.draw_date) : null;
    if (d && !Number.isNaN(d.getTime())) {
      drawWhen = d.toLocaleString('en-IN', { dateStyle: 'medium', timeStyle: 'short' });
    }
  } catch {
    drawWhen = '';
  }

  const prizeHtml = formatInr(draw.prize_amount);

  const html = `<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>${escapeHtml(title)}</title>
    <meta property="og:title" content="${escapeHtml(title)}" />
    <meta property="og:description" content="${escapeHtml(subtitle)}" />
    <meta name="description" content="${escapeHtml(subtitle)}" />
    <meta name="robots" content="noindex,nofollow" />
    <style>
      :root { color-scheme: light dark; }
      body { font-family: system-ui, -apple-system, Segoe UI, Arial, sans-serif; margin: 0; padding: 32px; background: linear-gradient(160deg, #0f172a 0%, #1e293b 100%); color: #f1f5f9; min-height: 100vh; }
      .card { max-width: 720px; margin: 0 auto; background: rgba(255,255,255,0.07); border: 1px solid rgba(255,255,255,0.12); border-radius: 18px; padding: 28px; box-shadow: 0 20px 50px rgba(0,0,0,0.35); }
      .kicker { letter-spacing: 0.1em; text-transform: uppercase; font-size: 11px; opacity: 0.75; }
      h1 { font-size: 26px; margin: 8px 0 4px; font-weight: 700; }
      .sub { font-size: 14px; opacity: 0.85; margin-bottom: 18px; }
      .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-top: 8px; }
      .item { background: rgba(0,0,0,0.25); border: 1px solid rgba(255,255,255,0.1); border-radius: 14px; padding: 14px 16px; }
      .label { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; opacity: 0.65; }
      .value { font-size: 17px; margin-top: 6px; font-weight: 600; }
      .footer { margin-top: 22px; padding-top: 16px; border-top: 1px solid rgba(255,255,255,0.1); font-size: 12px; opacity: 0.72; line-height: 1.5; }
      .badge { display: inline-block; margin-top: 12px; padding: 6px 10px; border-radius: 999px; background: rgba(34,197,94,0.2); color: #86efac; font-size: 12px; font-weight: 600; }
      @media (max-width: 640px) { body { padding: 16px; } .grid { grid-template-columns: 1fr; } h1 { font-size: 22px; } }
    </style>
  </head>
  <body>
    <div class="card">
      <div class="kicker">LuckyChit · Public draw result</div>
      <h1>${escapeHtml(groupName)}</h1>
      <p class="sub">Month <strong>${escapeHtml(String(draw.month))}</strong> · Year <strong>${escapeHtml(String(draw.year))}</strong>${drawWhen ? ` · ${escapeHtml(drawWhen)}` : ''}</p>
      <span class="badge">Anyone with this link can view this page</span>
      <div class="grid">
        <div class="item">
          <div class="label">Winner</div>
          <div class="value">${escapeHtml(winnerName)}</div>
        </div>
        <div class="item">
          <div class="label">Prize</div>
          <div class="value">${prizeHtml}</div>
        </div>
        <div class="item">
          <div class="label">Active members (group)</div>
          <div class="value">${escapeHtml(String(totalMembers))}</div>
        </div>
        <div class="item">
          <div class="label">Status</div>
          <div class="value">${escapeHtml(draw.status || '—')}</div>
        </div>
      </div>
      <div class="footer">
        This page is shared via a signed link so results stay verifiable. Bookmark it to open anytime.
      </div>
    </div>
  </body>
</html>`;

  res.setHeader('Content-Type', 'text/html; charset=utf-8');
  res.setHeader('Cache-Control', 'public, max-age=300');
  return res.status(200).send(html);
}

/**
 * Preferred: GET /share/draw?t=<jwt> — short path; avoids ENAMETOOLONG behind Nginx/static rules.
 */
router.get('/draw', async (req, res) => {
  try {
    const raw = req.query.t ?? req.query.token;
    const token = typeof raw === 'string' ? raw.trim() : '';
    if (!token) {
      return res
        .status(400)
        .send('Missing token. Use the full link from WhatsApp (it should include ?t=…).');
    }
    return await renderDrawSharePage(req, res, token);
  } catch (error) {
    console.error('Public draw share error:', error);
    return res.status(500).send('Server error.');
  }
});

/**
 * Legacy: GET /share/draw/:token — may fail on some hosts (path segment too long → ENAMETOOLONG).
 */
router.get('/draw/:token', async (req, res) => {
  try {
    const token = String(req.params.token || '').trim();
    if (!token) {
      return res.status(400).send('Missing token.');
    }
    return await renderDrawSharePage(req, res, token);
  } catch (error) {
    console.error('Public draw share error:', error);
    return res.status(500).send('Server error.');
  }
});

module.exports = router;
