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

@Controller('whatsapp/quantity')
export class QuantityWebviewController {
  private readonly logger = new Logger(QuantityWebviewController.name);

  constructor(private readonly prisma: PrismaService) {}

  @Get()
  async serveQuantitySelector(
    @Query('productId') productId: string,
    @Query('phone') phone: string,
    @Query('businessId') businessId: string,
    @Res() res: express.Response,
  ) {
    this.logger.log(`Quantity webview requested for product: ${productId}, phone: ${phone}`);

    const product = await this.prisma.product.findUnique({
      where: { id: productId || '' },
    });

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

    const safeName = this.esc(product.name);
    const safePrice = product.price;
    const safeImg = product.imageUrl || 'https://images.unsplash.com/photo-1584269600464-37b1b58a9fe7?q=80&w=400';
    const safePhone = this.esc(phone || '');
    const safeBusinessId = this.esc(businessId || '');
    const inStock = product.stockQuantity === null || product.stockQuantity > 0;

    const html = `<!DOCTYPE html>
<html class="light" lang="en">
<head>
  <meta charset="utf-8"/>
  <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
  <title>RetailBot - Quantity Selection</title>
  <script src="https://cdn.tailwindcss.com?plugins=forms,container-queries"></script>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=Hanken+Grotesk:wght@600;700;800&family=JetBrains+Mono:wght@500&family=Material+Symbols+Outlined:wght,FILL@100..700,0..1&display=swap" rel="stylesheet"/>
  <script id="tailwind-config">
    tailwind.config = {
      darkMode: "class",
      theme: {
        extend: {
          "colors": {
            "surface-dim": "#d8dadd",
            "on-primary-fixed": "#002109",
            "surface-bright": "#f7f9fc",
            "secondary-fixed": "#a8f0e3",
            "inverse-on-surface": "#eff1f4",
            "on-secondary": "#ffffff",
            "tertiary-fixed": "#c4e7ff",
            "primary": "#006d2f",
            "on-tertiary-fixed": "#001e2c",
            "tertiary-container": "#48c4ff",
            "bubble-out": "#E7FFDB",
            "on-secondary-container": "#226e63",
            "on-primary-container": "#005523",
            "on-secondary-fixed-variant": "#005047",
            "surface-container-low": "#f2f4f7",
            "status-blue": "#34B7F1",
            "surface-variant": "#e0e3e6",
            "secondary": "#1c695f",
            "secondary-container": "#a5ede0",
            "error": "#ba1a1a",
            "on-error-container": "#93000a",
            "on-primary-fixed-variant": "#005322",
            "on-tertiary": "#ffffff",
            "outline-variant": "#bbcbb9",
            "on-surface": "#191c1e",
            "surface-container-lowest": "#ffffff",
            "secondary-fixed-dim": "#8cd4c7",
            "on-tertiary-container": "#004f6c",
            "error-container": "#ffdad6",
            "bubble-in": "#FFFFFF",
            "primary-container": "#25d366",
            "inverse-primary": "#3de273",
            "on-background": "#191c1e",
            "outline": "#6c7b6b",
            "retail-dark": "#111B21",
            "surface-container-highest": "#e0e3e6",
            "on-primary": "#ffffff",
            "on-error": "#ffffff",
            "surface-container-high": "#e6e8eb",
            "background": "#f7f9fc",
            "surface-tint": "#006d2f",
            "tertiary": "#00668a",
            "surface": "#f7f9fc",
            "surface-container": "#eceef1",
            "on-tertiary-fixed-variant": "#004c69",
            "primary-fixed": "#66ff8e",
            "primary-fixed-dim": "#3de273",
            "whatsapp-teal": "#128C7E",
            "tertiary-fixed-dim": "#7cd0ff",
            "on-surface-variant": "#3c4a3d",
            "inverse-surface": "#2d3133",
            "on-secondary-fixed": "#00201c"
          },
          "borderRadius": {
            "DEFAULT": "0.25rem",
            "lg": "0.5rem",
            "xl": "0.75rem",
            "full": "9999px"
          },
          "spacing": {
            "stack-gap": "4px",
            "section-gap": "16px",
            "bubble-padding": "8px 12px",
            "container-margin": "12px",
            "gutter": "12px"
          },
          "fontFamily": {
            "label-md": ["JetBrains Mono"],
            "body-lg": ["Inter"],
            "headline-lg": ["Hanken Grotesk"],
            "headline-md": ["Hanken Grotesk"],
            "body-md": ["Inter"],
            "cta-label": ["Hanken Grotesk"],
            "headline-lg-mobile": ["Hanken Grotesk"]
          },
          "fontSize": {
            "label-md": ["12px", {"lineHeight": "16px", "letterSpacing": "0.02em", "fontWeight": "500"}],
            "body-lg": ["16px", {"lineHeight": "24px", "fontWeight": "400"}],
            "headline-lg": ["24px", {"lineHeight": "32px", "fontWeight": "700"}],
            "headline-md": ["20px", {"lineHeight": "28px", "fontWeight": "600"}],
            "body-md": ["14px", {"lineHeight": "20px", "fontWeight": "400"}],
            "cta-label": ["14px", {"lineHeight": "20px", "fontWeight": "600"}],
            "headline-lg-mobile": ["20px", {"lineHeight": "28px", "fontWeight": "700"}]
          }
        },
      },
    }
  </script>
  <style>
    .material-symbols-outlined {
      font-variation-settings: "FILL" 0, "wght" 400, "GRAD" 0, "opsz" 24
    }
    .whatsapp-bg {
      background-image: url(https://lh3.googleusercontent.com/aida-public/AB6AXuBqO9ua858tQ2cigFUn2twBpZ0-ug_rilUuylrH3vb7qKwELqUGRmNQthm7KkH8235EY3I_qXWz7HXPSke-t1dVrhZHuIukTm5AvUt4CSMtQ0N7wazK80XywxtQhnO1439FE6i6I5pR7-qaroJgGEUoTD1VOmG0zWUBLRPmKMOTeLxRxS1LqCzHphGmY0DAJfQWWiTPMcCsqauQPEq6OrOpYcoddy2EPEJQRiCTw12nDzEVyR70pOXljOTh2hh3P6atGm4QYoScoozz);
      background-repeat: repeat;
      background-size: 400px;
      opacity: 0.06;
    }
    @keyframes slideUp {
      from { transform: translateY(100%); }
      to { transform: translateY(0); }
    }
    .animate-slide-up {
      animation: slideUp 0.3s ease-out forwards;
    }
    body {
      min-height: max(884px, 100dvh);
    }
    /* Hide number input spinners */
    input[type=number]::-webkit-inner-spin-button, 
    input[type=number]::-webkit-outer-spin-button { 
      -webkit-appearance: none; 
      margin: 0; 
    }
    input[type=number] {
      -moz-appearance: textfield;
    }
  </style>
</head>
<body class="bg-surface text-on-surface font-body-md min-h-screen flex justify-center overflow-hidden">

  <!-- Mock Background Chat Thread (Blurred/Dimmed) -->
  <div class="w-full max-w-[480px] h-screen bg-[#E5DDD5] relative overflow-hidden flex flex-col pointer-events-none filter blur-sm grayscale-[20%]">
    <div class="absolute inset-0 whatsapp-bg"></div>
    <header class="fixed top-0 left-0 w-full z-50 flex items-center px-container-margin py-2 h-14 bg-whatsapp-teal text-on-primary shadow-sm">
      <span class="material-symbols-outlined mr-3">arrow_back</span>
      <div class="w-10 h-10 rounded-full bg-surface-container-highest mr-3"></div>
      <div class="flex-1">
        <h1 class="font-headline-md text-headline-md-mobile font-bold">RetailBot</h1>
        <p class="text-[11px] opacity-80">online</p>
      </div>
      <span class="material-symbols-outlined">more_vert</span>
    </header>
    <main class="flex-1 pt-16 pb-20 px-3 flex flex-col gap-4">
      <div class="self-end bg-bubble-out p-bubble-padding rounded-lg shadow-sm max-w-[85%] relative">
        <p class="text-body-md">Hello! I'm looking for some premium coffee beans. Do you have organic options?</p>
        <span class="text-[10px] text-on-surface-variant float-right ml-2 mt-1">09:41 AM</span>
      </div>
      <div class="self-start bg-bubble-in p-bubble-padding rounded-lg shadow-sm max-w-[85%] relative">
        <p class="text-body-md mb-2">Of course! Our ${safeName} is a customer favorite. Here are the details:</p>
        <div class="bg-surface-container-low rounded-xl overflow-hidden border border-outline-variant">
          <img class="w-full aspect-square object-cover" src="${safeImg}"/>
          <div class="p-3">
            <div class="flex justify-between items-start mb-1">
              <h3 class="font-headline-md text-headline-md-mobile">${safeName}</h3>
              <span class="font-label-md text-label-md text-primary">$${safePrice.toFixed(2)}</span>
            </div>
            <p class="text-xs text-on-surface-variant mb-3">${this.esc(product.description || 'Premium quality, ethically sourced.')}</p>
            <button class="w-full bg-primary-container text-on-primary-container py-2 rounded-lg font-cta-label">Add to Cart</button>
          </div>
        </div>
        <span class="text-[10px] text-on-surface-variant float-right ml-2 mt-1">09:42 AM</span>
      </div>
    </main>
  </div>

  <!-- QUANTITY SELECTION OVERLAY (WHATSAPP FLOW STYLE) -->
  <div class="fixed inset-0 z-[100] flex items-end justify-center bg-black/40 backdrop-blur-[2px]">
    <div class="w-full max-w-[480px] bg-surface-container-lowest rounded-t-[24px] shadow-2xl animate-slide-up flex flex-col max-h-[795px]">
      <div class="w-12 h-1.5 bg-surface-variant rounded-full mx-auto mt-3 mb-1"></div>
      
      <div class="flex items-center justify-between px-6 py-4">
        <h2 class="font-headline-lg text-headline-lg-mobile text-on-surface">Select Quantity</h2>
        <button class="p-2 hover:bg-surface-variant rounded-full transition-colors border-0 bg-transparent cursor-pointer" onclick="closeWindow()">
          <span class="material-symbols-outlined text-on-surface-variant">close</span>
        </button>
      </div>

      <div class="px-6 py-4 flex items-center gap-4 bg-surface-container-low/50">
        <div class="w-20 h-20 rounded-xl overflow-hidden shadow-sm flex-shrink-0">
          <img class="w-full h-full object-cover" src="${safeImg}"/>
        </div>
        <div class="flex-1">
          <h3 class="font-headline-md text-headline-md-mobile text-on-surface">${safeName}</h3>
          <p class="text-on-surface-variant text-body-md">$${safePrice.toFixed(2)} per unit</p>
          <div class="flex items-center gap-1 mt-1">
            <span class="material-symbols-outlined text-[16px] text-status-blue" style="font-variation-settings: 'FILL' 1;">verified</span>
            <span class="text-[11px] font-label-md text-status-blue">${inStock ? 'In Stock' : 'Out of Stock'}</span>
          </div>
        </div>
      </div>

      <div class="flex-1 flex flex-col items-center justify-center py-12 px-6">
        <div class="flex items-center gap-8 mb-8">
          <button class="w-14 h-14 rounded-full border-2 border-primary flex items-center justify-center text-primary hover:bg-primary/5 active:scale-90 transition-all disabled:opacity-30 disabled:border-outline cursor-pointer bg-white" id="minus-btn" onclick="updateQty(-1)">
            <span class="material-symbols-outlined text-3xl">remove</span>
          </button>
          <div class="text-center w-24">
            <input 
              type="number" 
              id="qty-input" 
              value="1" 
              min="1" 
              max="99" 
              oninput="handleInputQty(this)"
              class="w-full text-center text-5xl font-headline-lg font-extrabold text-on-surface bg-transparent border-0 border-b-2 border-dashed border-primary/50 focus:border-solid focus:border-primary focus:ring-0 focus:outline-none py-1 tabular-nums"
            />
            <p class="text-on-surface-variant font-label-md uppercase tracking-wider mt-2">Units</p>
          </div>
          <button class="w-14 h-14 rounded-full border-2 border-primary flex items-center justify-center text-primary hover:bg-primary/5 active:scale-90 transition-all cursor-pointer bg-white" id="plus-btn" onclick="updateQty(1)">
            <span class="material-symbols-outlined text-3xl">add</span>
          </button>
        </div>
        <div class="bg-secondary-container/30 px-6 py-3 rounded-full flex items-center gap-3">
          <span class="text-on-secondary-container font-body-md">Subtotal:</span>
          <span class="text-on-secondary-container font-headline-md font-bold" id="subtotal-display">$${safePrice.toFixed(2)}</span>
        </div>
      </div>

      <div class="p-6 border-t border-outline-variant bg-surface-container-lowest">
        <button class="w-full bg-whatsapp-teal text-white py-4 rounded-xl font-cta-label text-lg shadow-lg active:scale-[0.98] transition-transform flex items-center justify-center gap-2 border-0 cursor-pointer" onclick="confirmPurchase()">
          <span class="material-symbols-outlined">shopping_cart_checkout</span>
          Confirm Quantity
        </button>
        <p class="text-center text-[11px] text-on-surface-variant mt-4 opacity-70">
          Secure checkout powered by RetailBot. Your order will be added to your chat basket.
        </p>
      </div>
    </div>
  </div>

  <nav class="fixed bottom-0 w-full z-50 flex justify-around items-center px-4 py-2 bg-surface-container border-t border-outline-variant md:hidden pointer-events-none opacity-50">
    <div class="flex flex-col items-center justify-center bg-secondary-container text-on-secondary-container rounded-full p-2">
      <span class="material-symbols-outlined" style="font-variation-settings: 'FILL' 1;">chat</span>
    </div>
    <div class="flex flex-col items-center justify-center text-on-surface-variant p-2">
      <span class="material-symbols-outlined">store</span>
    </div>
    <div class="flex flex-col items-center justify-center text-on-surface-variant p-2">
      <span class="material-symbols-outlined">shopping_cart</span>
    </div>
    <div class="flex flex-col items-center justify-center text-on-surface-variant p-2">
      <span class="material-symbols-outlined">person</span>
    </div>
  </nav>

  <script>
    let quantity = 1;
    const unitPrice = ${safePrice};
    
    const qtyInput = document.getElementById('qty-input');
    const subtotalDisplay = document.getElementById('subtotal-display');
    const minusBtn = document.getElementById('minus-btn');

    function handleInputQty(inputEl) {
      let val = parseInt(inputEl.value.trim());
      if (isNaN(val) || val < 1) {
        val = 1;
      } else if (val > 99) {
        val = 99;
      }
      quantity = val;
      inputEl.value = val;
      render();
    }

    function updateQty(delta) {
      const newQty = quantity + delta;
      if (newQty >= 1 && newQty <= 99) {
        quantity = newQty;
        qtyInput.value = quantity;
        render();
        if (window.navigator && window.navigator.vibrate) {
          window.navigator.vibrate(10);
        }
      }
    }

    function render() {
      const total = (quantity * unitPrice).toFixed(2);
      subtotalDisplay.textContent = '$' + total;
      minusBtn.disabled = quantity <= 1;

      qtyInput.classList.add('scale-105', 'text-primary');
      setTimeout(() => {
        qtyInput.classList.remove('scale-105', 'text-primary');
      }, 100);
    }

    function confirmPurchase() {
      const btn = event.currentTarget;
      const originalContent = btn.innerHTML;
      btn.innerHTML = '<span class="material-symbols-outlined animate-spin">sync</span> Adding...';
      btn.disabled = true;
      
      const payload = {
        businessId: "${safeBusinessId}",
        whatsappNumber: "${safePhone}",
        productId: "${productId}",
        quantity: quantity
      };

      fetch('/webhooks/whatsapp/webview-confirm', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          btn.innerHTML = '<span class="material-symbols-outlined">check_circle</span> Added to Basket';
          btn.classList.replace('bg-whatsapp-teal', 'bg-primary');
          setTimeout(() => {
            alert(\`Confirmed: \${quantity} units added successfully! You can close this tab and return to WhatsApp.\`);
          }, 500);
        } else {
          alert('Failed to add items: ' + (data.error || 'Unknown error'));
          btn.innerHTML = originalContent;
          btn.disabled = false;
        }
      })
      .catch(err => {
        alert('Network error. Please try again.');
        btn.innerHTML = originalContent;
        btn.disabled = false;
      });
    }

    function closeWindow() {
      window.close();
      alert('You can now close this browser tab and return to WhatsApp.');
    }

    render();
  </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;');
  }
}
