import { Controller, Get, Query, Res, Logger } from '@nestjs/common';
import * as express from 'express';

@Controller('payments/checkout')
export class CheckoutController {
  private readonly logger = new Logger(CheckoutController.name);

  @Get()
  serveCheckout(
    @Query('reference') reference: string,
    @Query('amount') amount: string,
    @Query('currency') currency: string,
    @Query('orderId') orderId: string,
    @Query('email') email: string,
    @Res() res: express.Response,
  ) {
    this.logger.log(`Checkout page requested: ref=${reference}, amount=${amount}, currency=${currency}`);

    const safeRef = this.esc(reference || '');
    const safeAmount = this.esc(amount || '0.00');
    const safeCurrency = this.esc(currency || 'USD');
    const safeEmail = this.esc(email || '');
    const safeOrderId = this.esc(orderId || '');

    // The backend's own public URL (ngrok URL). Used to call the webhook from the browser.
    const backendPublicUrl = process.env.PUBLIC_URL || '';

    const html = `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Secure Payment – WhatsApp Commerce Hub</title>
  <style>
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      min-height: 100vh;
      display: flex; align-items: center; justify-content: center;
      background: #090a0f;
      font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
      color: #e2e8f0;
      padding: 1rem;
    }
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
    .card {
      background: rgba(255,255,255,0.04);
      border: 1px solid rgba(255,255,255,0.08);
      border-radius: 1.25rem;
      padding: 2rem;
      width: 100%; max-width: 420px;
      position: relative; overflow: hidden;
      box-shadow: 0 25px 50px rgba(0,0,0,0.5);
      backdrop-filter: blur(12px);
    }
    .glow-tl {
      position:absolute; top:-60px; left:-60px; width:160px; height:160px;
      background: radial-gradient(circle, rgba(16,185,129,0.15), transparent 70%);
      border-radius:50%; pointer-events:none;
    }
    .glow-br {
      position:absolute; bottom:-60px; right:-60px; width:160px; height:160px;
      background: radial-gradient(circle, rgba(6,182,212,0.12), transparent 70%);
      border-radius:50%; pointer-events:none;
    }
    .header { display:flex; align-items:center; gap:0.75rem; padding-bottom:1rem; border-bottom:1px solid rgba(255,255,255,0.06); margin-bottom:1.5rem; }
    .icon-wrap { width:40px; height:40px; border-radius:0.75rem; background:rgba(6,182,212,0.1); border:1px solid rgba(6,182,212,0.2); display:flex; align-items:center; justify-content:center; flex-shrink:0; }
    .icon-wrap svg { width:20px; height:20px; stroke:#22d3ee; fill:none; stroke-width:2; stroke-linecap:round; stroke-linejoin:round; }
    .header-text h1 { font-size:0.95rem; font-weight:700; color:#fff; }
    .header-text small { font-size:0.65rem; font-family:monospace; color:#6b7280; word-break:break-all; }
    .amount-box { background:rgba(0,0,0,0.25); border:1px solid rgba(255,255,255,0.06); border-radius:0.75rem; padding:1rem; display:flex; justify-content:space-between; align-items:center; margin-bottom:1.25rem; }
    .amount-label { font-size:0.7rem; color:#9ca3af; text-transform:uppercase; letter-spacing:0.05em; }
    .amount-value { font-size:1.4rem; font-weight:800; font-family:monospace; color:#fff; }
    .info-row { background:rgba(255,255,255,0.03); border:1px solid rgba(255,255,255,0.06); border-radius:0.6rem; padding:0.75rem 1rem; font-size:0.75rem; color:#9ca3af; margin-bottom:0.5rem; }
    .info-row strong { color:#e2e8f0; }
    .section-label { font-size:0.6rem; font-weight:700; text-transform:uppercase; letter-spacing:0.08em; color:#6b7280; margin-bottom:0.75rem; margin-top:1rem; }
    .actions { display:flex; flex-direction:column; gap:0.75rem; padding-top:1rem; border-top:1px solid rgba(255,255,255,0.06); margin-top:1rem; }
    .btn { width:100%; padding:0.85rem; border-radius:0.75rem; font-size:0.85rem; font-weight:600; border:none; cursor:pointer; transition:all 0.2s; }
    .btn:disabled { opacity:0.5; cursor:not-allowed; }
    .btn-success { background:linear-gradient(135deg,#10b981,#059669); color:#fff; box-shadow:0 4px 15px rgba(16,185,129,0.2); }
    .btn-success:hover:not(:disabled) { background:linear-gradient(135deg,#059669,#047857); transform:translateY(-1px); }
    .btn-fail { background:rgba(239,68,68,0.1); border:1px solid rgba(239,68,68,0.2); color:#f87171; }
    .btn-fail:hover:not(:disabled) { background:rgba(239,68,68,0.18); }
    .status { display:none; padding:0.75rem; border-radius:0.75rem; font-size:0.8rem; text-align:center; margin-top:0.5rem; }
    .status.success { display:block; background:rgba(16,185,129,0.1); border:1px solid rgba(16,185,129,0.25); color:#6ee7b7; }
    .status.error { display:block; background:rgba(239,68,68,0.1); border:1px solid rgba(239,68,68,0.2); color:#f87171; }
    .status.processing { display:block; background:rgba(251,191,36,0.1); border:1px solid rgba(251,191,36,0.2); color:#fcd34d; }
    .success-screen { display:none; text-align:center; padding:2rem 0; }
    .success-screen.show { display:block; }
    .success-icon { width:64px; height:64px; border-radius:50%; background:rgba(16,185,129,0.1); border:1px solid rgba(16,185,129,0.2); display:flex; align-items:center; justify-content:center; margin:0 auto 1rem; }
    .success-icon svg { width:36px; height:36px; stroke:#10b981; fill:none; stroke-width:2.5; stroke-linecap:round; stroke-linejoin:round; }
    .success-screen h2 { font-size:1.4rem; font-weight:800; color:#fff; margin-bottom:0.5rem; }
    .success-screen p { font-size:0.8rem; color:#9ca3af; line-height:1.6; max-width:280px; margin:0 auto; }
    .whatsapp-note { margin-top:1rem; background:rgba(18,140,126,0.12); border:1px solid rgba(18,140,126,0.3); color:#6ee7b7; padding:0.65rem 0.85rem; border-radius:0.6rem; font-size:0.72rem; line-height:1.5; }
    #main-form { display:block; }
  </style>
</head>
<body>
<div class="card">
  <div class="glow-tl"></div>
  <div class="glow-br"></div>

  <!-- Success Screen -->
  <div class="success-screen" id="success-screen">
    <div class="success-icon">
      <svg viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg>
    </div>
    <h2>Payment Confirmed!</h2>
    <p>Your payment of <strong>${safeCurrency} $${safeAmount}</strong> has been successfully processed.</p>
    <div class="whatsapp-note">
      💬 A confirmation has been sent to your WhatsApp. You can now close this tab and return to the chat.
    </div>
  </div>

  <!-- Main Form -->
  <div id="main-form">
    <div class="header">
      <div class="icon-wrap">
        <svg viewBox="0 0 24 24"><path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 01-8 0"/></svg>
      </div>
      <div class="header-text">
        <h1>Secure Payment Checkout</h1>
        <small>Ref: ${safeRef}</small>
      </div>
    </div>

    <div class="amount-box">
      <span class="amount-label">Total Amount Due</span>
      <span class="amount-value">${safeCurrency} $${parseFloat(safeAmount || '0').toFixed(2)}</span>
    </div>

    <div class="section-label">Payment Details</div>
    <div class="info-row">Email: <strong>${safeEmail || 'N/A'}</strong></div>
    <div class="info-row">Order: <strong>#${safeOrderId || 'N/A'}</strong></div>
    <div class="info-row">Gateway: <strong>WhatsApp Commerce Hub (Sandbox)</strong></div>

    <div id="status-msg" class="status"></div>

    <div class="actions">
      <button class="btn btn-success" id="btn-success" onclick="simulate('SUCCESS')">
        ✅ Confirm & Complete Payment
      </button>
      <button class="btn btn-fail" id="btn-fail" onclick="simulate('FAILED')">
        ✗ Decline Payment
      </button>
    </div>
  </div>
</div>

<script>
  var BACKEND_URL = ${backendPublicUrl ? `'${backendPublicUrl}'` : 'window.location.origin'};

  function setStatus(msg, type) {
    var el = document.getElementById('status-msg');
    el.textContent = msg;
    el.className = 'status ' + type;
  }

  function setButtons(disabled) {
    document.getElementById('btn-success').disabled = disabled;
    document.getElementById('btn-fail').disabled = disabled;
  }

  async function simulate(status) {
    setButtons(true);
    setStatus('Processing your transaction...', 'processing');

    var gtwRef = 'GTW-' + status + '-' + Math.floor(100000 + Math.random() * 900000);

    try {
      var resp = await fetch(BACKEND_URL + '/webhooks/payments/mock', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          reference: '${safeRef}',
          status: status,
          gatewayReference: status === 'SUCCESS' ? gtwRef : undefined,
        }),
      });

      if (!resp.ok) throw new Error('Server responded with ' + resp.status);

      if (status === 'SUCCESS') {
        document.getElementById('main-form').style.display = 'none';
        document.getElementById('success-screen').classList.add('show');
      } else {
        setStatus('Payment declined. Please try again or use a different method.', 'error');
        setButtons(false);
      }
    } catch (err) {
      setStatus('Error: ' + (err.message || 'Network failure. Check your connection.'), 'error');
      setButtons(false);
    }
  }
</script>
</body>
</html>`;

    res.setHeader('Content-Type', 'text/html; charset=utf-8');
    res.setHeader('Cache-Control', 'no-store');
    res.send(html);
  }

  private esc(str: string): string {
    return str
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#x27;');
  }
}
