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

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

  constructor(private readonly prisma: PrismaService) {}

  @Get('search')
  async serveSearchFlow(
    @Query('phone') phone: string,
    @Query('businessId') businessId: string,
    @Res() res: express.Response,
  ) {
    this.logger.log(`Search webview requested for phone: ${phone}, business: ${businessId}`);

    const business = await this.prisma.business.findUnique({
      where: { id: businessId || '' },
    });
    const businessName = this.esc(business?.name || 'our Store');
    const safePhone = this.esc(phone || '');
    const safeBusinessId = this.esc(businessId || '');

    const html = `<!DOCTYPE html>
<html class="dark" lang="en">
<head>
  <meta charset="utf-8"/>
  <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
  <title>Search Products</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;700&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: {
            "wa-bg": "#111b21",
            "wa-surface": "#121b22",
            "wa-input": "#202c33",
            "wa-border": "#2a3942",
            "wa-green": "#00a884",
            "wa-text": "#e9edef",
            "wa-text-secondary": "#8696a0",
            "wa-btn-disabled": "#202c33",
            "wa-btn-text-disabled": "#8696a0",
          }
        }
      }
    }
  </script>
  <style>
    body {
      background-color: #111b21;
      color: #e9edef;
      font-family: 'Inter', sans-serif;
    }
    @keyframes slideUp {
      from { transform: translateY(100%); }
      to { transform: translateY(0); }
    }
    .animate-slide-up {
      animation: slideUp 0.3s ease-out forwards;
    }
  </style>
</head>
<body class="min-h-screen flex justify-center items-end sm:items-center p-0 sm:p-4">
  <div class="w-full max-w-[480px] h-screen sm:h-[840px] bg-wa-bg flex flex-col justify-between shadow-2xl relative sm:rounded-[24px] overflow-hidden border border-wa-border/30">
    
    <!-- Header -->
    <div>
      <div class="flex items-center justify-between px-6 py-4 bg-wa-bg">
        <button class="p-2 hover:bg-wa-input rounded-full transition-colors border-0 bg-transparent cursor-pointer" onclick="closeWindow()">
          <span class="material-symbols-outlined text-wa-text text-xl">close</span>
        </button>
        <span class="text-sm font-semibold tracking-wide text-wa-text">Search Products</span>
        <button class="p-2 hover:bg-wa-input rounded-full transition-colors border-0 bg-transparent cursor-pointer">
          <span class="material-symbols-outlined text-wa-text text-xl">more_vert</span>
        </button>
      </div>
      <!-- Progress Bar (50% for search step) -->
      <div class="w-full h-1 bg-wa-border">
        <div class="h-full w-1/2 bg-wa-green transition-all duration-300"></div>
      </div>
    </div>

    <!-- Main Content Form -->
    <div class="flex-1 px-6 py-8 flex flex-col justify-start">
      <h2 class="text-2xl font-bold mb-2 text-wa-text">Search Products</h2>
      <p class="text-sm text-wa-text-secondary mb-8">Please enter product search terms or keywords below.</p>

      <div class="space-y-6">
        <div class="relative">
          <input 
            type="text" 
            id="search-query" 
            placeholder="Search Keyword" 
            oninput="validateForm()"
            class="w-full bg-transparent border border-wa-border focus:border-wa-green focus:ring-1 focus:ring-wa-green text-wa-text rounded-xl px-4 py-4 placeholder-wa-text-secondary outline-none transition-all text-base"
          />
          <p class="text-xs text-wa-text-secondary mt-1.5 px-1">Example: Coffee, Mouse, Speaker</p>
        </div>
      </div>
    </div>

    <!-- Bottom Action Button & Footer -->
    <div class="p-6 bg-wa-bg border-t border-wa-border/50">
      <button 
        id="submit-btn"
        disabled
        onclick="submitSearch()"
        class="w-full bg-wa-btn-disabled text-wa-btn-text-disabled py-4 rounded-full font-bold text-base transition-all duration-200 border-0 cursor-pointer flex items-center justify-center gap-2"
      >
        Search Catalog
      </button>

      <div class="flex items-center justify-center gap-2 mt-6 text-xs text-wa-text-secondary">
        <div class="w-5 h-5 rounded-full bg-wa-green/10 flex items-center justify-center text-wa-green text-[10px] font-bold">✓</div>
        <span>Managed by <span class="font-semibold text-wa-text">${businessName}</span>. <a href="#" class="text-wa-green hover:underline">Learn more</a></span>
      </div>
    </div>
  </div>

  <script>
    const searchInput = document.getElementById('search-query');
    const submitBtn = document.getElementById('submit-btn');

    function validateForm() {
      const val = searchInput.value.trim();
      if (val.length >= 2) {
        submitBtn.disabled = false;
        submitBtn.classList.remove('bg-wa-btn-disabled', 'text-wa-btn-text-disabled');
        submitBtn.classList.add('bg-wa-green', 'text-wa-bg', 'hover:brightness-110');
      } else {
        submitBtn.disabled = true;
        submitBtn.classList.add('bg-wa-btn-disabled', 'text-wa-btn-text-disabled');
        submitBtn.classList.remove('bg-wa-green', 'text-wa-bg', 'hover:brightness-110');
      }
    }

    function submitSearch() {
      const btn = document.getElementById('submit-btn');
      const originalText = btn.innerText;
      btn.innerHTML = '<span class="material-symbols-outlined animate-spin text-sm">sync</span> Searching...';
      btn.disabled = true;

      const payload = {
        businessId: "${safeBusinessId}",
        whatsappNumber: "${safePhone}",
        query: searchInput.value.trim()
      };

      fetch('/webhooks/whatsapp/webview-search', {
        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 text-sm">check_circle</span> Results Sent!';
          btn.classList.replace('bg-wa-green', 'bg-wa-green/20');
          btn.classList.replace('text-wa-bg', 'text-wa-green');
          setTimeout(() => {
            closeWindow();
          }, 1200);
        } else {
          alert('Search failed: ' + (data.error || 'Unknown error'));
          btn.innerText = originalText;
          validateForm();
        }
      })
      .catch(err => {
        alert('Network error. Please try again.');
        btn.innerText = originalText;
        validateForm();
      });
    }

    function closeWindow() {
      window.close();
      alert('You can now close this tab and return to WhatsApp.');
    }
  </script>
</body>
</html>`;

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

  @Get('add-custom')
  async serveAddCustomFlow(
    @Query('phone') phone: string,
    @Query('businessId') businessId: string,
    @Query('productId') productId: string,
    @Res() res: express.Response,
  ) {
    this.logger.log(`Add custom product webview requested for phone: ${phone}, business: ${businessId}, product: ${productId}`);

    const business = await this.prisma.business.findUnique({
      where: { id: businessId || '' },
    });
    const businessName = this.esc(business?.name || 'our Store');
    const safePhone = this.esc(phone || '');
    const safeBusinessId = this.esc(businessId || '');
    const safeProductId = this.esc(productId || '');

    const product = productId
      ? await this.prisma.product.findUnique({ where: { id: productId } })
      : null;
    const productName = product ? product.name : '';

    const html = `<!DOCTYPE html>
<html class="dark" lang="en">
<head>
  <meta charset="utf-8"/>
  <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
  <title>Add Product</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;700&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: {
            "wa-bg": "#111b21",
            "wa-surface": "#121b22",
            "wa-input": "#202c33",
            "wa-border": "#2a3942",
            "wa-green": "#00a884",
            "wa-text": "#e9edef",
            "wa-text-secondary": "#8696a0",
            "wa-btn-disabled": "#202c33",
            "wa-btn-text-disabled": "#8696a0",
          }
        }
      }
    }
  </script>
  <style>
    body {
      background-color: #111b21;
      color: #e9edef;
      font-family: 'Inter', sans-serif;
    }
  </style>
</head>
<body class="min-h-screen flex justify-center items-end sm:items-center p-0 sm:p-4">
  <div class="w-full max-w-[480px] h-screen sm:h-[840px] bg-wa-bg flex flex-col justify-between shadow-2xl relative sm:rounded-[24px] overflow-hidden border border-wa-border/30">
    
    <!-- Header -->
    <div>
      <div class="flex items-center justify-between px-6 py-4 bg-wa-bg">
        <button class="p-2 hover:bg-wa-input rounded-full transition-colors border-0 bg-transparent cursor-pointer" onclick="closeWindow()">
          <span class="material-symbols-outlined text-wa-text text-xl">close</span>
        </button>
        <span class="text-sm font-semibold tracking-wide text-wa-text">Passenger Information</span>
        <button class="p-2 hover:bg-wa-input rounded-full transition-colors border-0 bg-transparent cursor-pointer">
          <span class="material-symbols-outlined text-wa-text text-xl">more_vert</span>
        </button>
      </div>
      <!-- Progress Bar (100% for info step) -->
      <div class="w-full h-1 bg-wa-border">
        <div class="h-full w-full bg-wa-green transition-all duration-300"></div>
      </div>
    </div>

    <!-- Main Content Form -->
    <div class="flex-1 px-6 py-8 flex flex-col justify-start">
      <h2 class="text-2xl font-bold mb-2 text-wa-text">Passenger Information</h2>
      <p class="text-sm text-wa-text-secondary mb-8">
        ${productName ? `Please enter details for <span class="text-wa-text font-semibold">${this.esc(productName)}</span> below.` : 'Please enter passenger details below.'}
      </p>

      <div class="space-y-6">
        <!-- Product Name / Passenger Name Input -->
        <div class="relative">
          <input 
            type="text" 
            id="product-name" 
            placeholder="Passenger Name" 
            oninput="validateForm()"
            class="w-full bg-transparent border border-wa-border focus:border-wa-green focus:ring-1 focus:ring-wa-green text-wa-text rounded-xl px-4 py-4 placeholder-wa-text-secondary outline-none transition-all text-base"
          />
          <p class="text-xs text-wa-text-secondary mt-1.5 px-1">Example: John Doe</p>
        </div>

        <!-- Quantity Input -->
        <div class="relative">
          <input 
            type="number" 
            id="product-qty" 
            placeholder="Quantity" 
            oninput="validateForm()"
            min="1"
            value="1"
            class="w-full bg-transparent border border-wa-border focus:border-wa-green focus:ring-1 focus:ring-wa-green text-wa-text rounded-xl px-4 py-4 placeholder-wa-text-secondary outline-none transition-all text-base"
          />
          <p class="text-xs text-wa-text-secondary mt-1.5 px-1">Example: 1</p>
        </div>
      </div>
    </div>

    <!-- Bottom Action Button & Footer -->
    <div class="p-6 bg-wa-bg border-t border-wa-border/50">
      <button 
        id="submit-btn"
        disabled
        onclick="submitProduct()"
        class="w-full bg-wa-btn-disabled text-wa-btn-text-disabled py-4 rounded-full font-bold text-base transition-all duration-200 border-0 cursor-pointer flex items-center justify-center gap-2"
      >
        Continue
      </button>

      <div class="flex items-center justify-center gap-2 mt-6 text-xs text-wa-text-secondary">
        <div class="w-5 h-5 rounded-full bg-wa-green/10 flex items-center justify-center text-wa-green text-[10px] font-bold">✓</div>
        <span>Managed by <span class="font-semibold text-wa-text">${businessName}</span>. <a href="#" class="text-wa-green hover:underline">Learn more</a></span>
      </div>
    </div>
  </div>

  <script>
    const nameInput = document.getElementById('product-name');
    const qtyInput = document.getElementById('product-qty');
    const submitBtn = document.getElementById('submit-btn');

    function validateForm() {
      const name = nameInput.value.trim();
      const qty = parseInt(qtyInput.value.trim());

      if (name.length >= 2 && !isNaN(qty) && qty >= 1) {
        submitBtn.disabled = false;
        submitBtn.classList.remove('bg-wa-btn-disabled', 'text-wa-btn-text-disabled');
        submitBtn.classList.add('bg-wa-green', 'text-wa-bg', 'hover:brightness-110');
      } else {
        submitBtn.disabled = true;
        submitBtn.classList.add('bg-wa-btn-disabled', 'text-wa-btn-text-disabled');
        submitBtn.classList.remove('bg-wa-green', 'text-wa-bg', 'hover:brightness-110');
      }
    }

    function submitProduct() {
      const btn = document.getElementById('submit-btn');
      const originalText = btn.innerText;
      btn.innerHTML = '<span class="material-symbols-outlined animate-spin text-sm">sync</span> Adding...';
      btn.disabled = true;

      const payload = {
        businessId: "${safeBusinessId}",
        whatsappNumber: "${safePhone}",
        productId: "${safeProductId}",
        productName: nameInput.value.trim(),
        quantity: parseInt(qtyInput.value.trim())
      };

      fetch('/webhooks/whatsapp/webview-add-custom', {
        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 text-sm">check_circle</span> Added to Cart!';
          btn.classList.replace('bg-wa-green', 'bg-wa-green/20');
          btn.classList.replace('text-wa-bg', 'text-wa-green');
          setTimeout(() => {
            closeWindow();
          }, 1200);
        } else {
          alert('Add failed: ' + (data.error || 'Unknown error'));
          btn.innerText = originalText;
          validateForm();
        }
      })
      .catch(err => {
        alert('Network error. Please try again.');
        btn.innerText = originalText;
        validateForm();
      });
    }

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

    // Initial validation check
    validateForm();
  </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;');
  }
}
