import { NextRequest, NextResponse } from 'next/server';
import { withAuth } from '@/lib/api-guards';

// GET: Export consolidated commission report as a print-optimized PDF layout (HTML view)
export const GET = withAuth(async (req, { prisma }) => {
  try {
    const { searchParams } = req.nextUrl;
    const period = searchParams.get('period');

    const whereClause: any = {};
    if (period) whereClause.period = period;

    // Fetch settlements with collaborator, hotel, region and plan details
    const settlements = await prisma.settlement.findMany({
      where: whereClause,
      include: {
        colaborador: {
          include: {
            hotel: {
              include: {
                region: true
              }
            }
          }
        },
        plan: true
      },
      orderBy: [
        { period: 'desc' },
        { colaborador: { hotel: { region: { name: 'asc' } } } },
        { colaborador: { hotel: { name: 'asc' } } }
      ]
    });

    if (settlements.length === 0) {
      return new Response('<h1>No data found</h1>', {
        headers: { 'Content-Type': 'text/html' }
      });
    }

    // Format currency helper
    const formatCurrency = (val: any) => {
      const num = parseFloat(val.toString());
      return new Intl.NumberFormat('es-CO', {
        style: 'currency',
        currency: 'COP',
        minimumFractionDigits: 0
      }).format(num);
    };

    // Build regions and hotels tree structure for grouping
    const structuredData: Record<string, Record<string, any[]>> = {};
    let grandTotalPayout = 0;
    let grandTotalSales = 0;

    for (const s of settlements) {
      const regionName = s.colaborador.hotel.region.name;
      const hotelName = s.colaborador.hotel.name;
      const payout = parseFloat(s.totalPayout.toString());
      const sales = parseFloat(s.salesAmount.toString());

      if (!structuredData[regionName]) {
        structuredData[regionName] = {};
      }
      if (!structuredData[regionName][hotelName]) {
        structuredData[regionName][hotelName] = [];
      }
      structuredData[regionName][hotelName].push(s);

      if (s.status === 'APPROVED') {
        grandTotalPayout += payout;
        grandTotalSales += sales;
      }
    }

    const htmlContent = `
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>Reporte de Remuneraciones y Comisiones - ${period || 'Consolidado'}</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      color: #333;
      margin: 40px;
      padding: 0;
      background-color: #white;
    }
    .header {
      text-align: center;
      margin-bottom: 40px;
      border-bottom: 2px solid #333;
      padding-bottom: 20px;
    }
    .logo {
      font-size: 24px;
      font-weight: bold;
      color: #0b1a30;
      text-transform: uppercase;
      margin-bottom: 5px;
    }
    .subtitle {
      font-size: 16px;
      color: #666;
      margin-bottom: 10px;
    }
    .meta-info {
      font-size: 12px;
      color: #555;
    }
    .region-title {
      font-size: 18px;
      font-weight: bold;
      color: #0b1a30;
      background-color: #f2f2f2;
      padding: 8px;
      margin-top: 30px;
      margin-bottom: 15px;
      border-left: 5px solid #0056b3;
    }
    .hotel-title {
      font-size: 14px;
      font-weight: bold;
      color: #333;
      margin-top: 15px;
      margin-bottom: 10px;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      margin-bottom: 20px;
      font-size: 11px;
    }
    th, td {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: left;
    }
    th {
      background-color: #f9f9f9;
      font-weight: bold;
    }
    .amount {
      text-align: right;
    }
    .grand-totals {
      margin-top: 40px;
      border: 2px solid #333;
      padding: 15px;
      background-color: #fafafa;
    }
    .totals-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20px;
    }
    .total-item {
      font-size: 14px;
    }
    .signatures {
      margin-top: 80px;
      display: flex;
      justify-content: space-around;
      page-break-inside: avoid;
    }
    .signature-line {
      border-top: 1px solid #333;
      width: 200px;
      text-align: center;
      padding-top: 5px;
      font-size: 12px;
    }
    .noPrint-btn {
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 10px 20px;
      background-color: #0056b3;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-weight: bold;
      box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    }
    .noPrint-btn:hover {
      background-color: #004085;
    }

    @media print {
      body {
        margin: 20px;
        color: #000;
        background: #fff;
      }
      .noPrint-btn {
        display: none;
      }
      .pageBreak {
        page-break-after: always;
      }
    }
  </style>
</head>
<body>
  <button class="noPrint-btn" onclick="window.print()">Imprimir Reporte</button>

  <div class="header">
    <div class="logo">Hoteles Estelar</div>
    <div class="subtitle">Reporte de Liquidación de Remuneración Variable y Comisiones</div>
    <div class="meta-info">
      <strong>Periodo:</strong> ${period || 'Todos los periodos'} | 
      <strong>Fecha de Generación:</strong> ${new Date().toLocaleDateString('es-CO')}
    </div>
  </div>

  ${Object.entries(structuredData).map(([regionName, hotelsMap]) => `
    <div class="region-block">
      <div class="region-title">Región: ${regionName}</div>
      ${Object.entries(hotelsMap).map(([hotelName, list]) => `
        <div class="hotel-block">
          <div class="hotel-title">Hotel: ${hotelName}</div>
          <table>
            <thead>
              <tr>
                <th>Colaborador</th>
                <th>Plan</th>
                <th>Estado</th>
                <th class="amount">Meta</th>
                <th class="amount">Venta</th>
                <th class="amount">% Cumpl.</th>
                <th class="amount">Comisión</th>
                <th class="amount">Clawback</th>
                <th class="amount">Total Pagar</th>
              </tr>
            </thead>
            <tbody>
              ${list.map(s => `
                <tr>
                  <td>${s.colaborador.username}</td>
                  <td>${s.plan.code}</td>
                  <td>${s.status}</td>
                  <td class="amount">${formatCurrency(s.goalAmount)}</td>
                  <td class="amount">${formatCurrency(s.salesAmount)}</td>
                  <td class="amount">${(parseFloat(s.achievementPercentage.toString()) * 100).toFixed(1)}%</td>
                  <td class="amount">${formatCurrency(s.calculatedCommission)}</td>
                  <td class="amount">${formatCurrency(s.adjustmentAmount)}</td>
                  <td class="amount"><strong>${formatCurrency(s.totalPayout)}</strong></td>
                </tr>
              `).join('')}
            </tbody>
          </table>
        </div>
      `).join('')}
    </div>
  `).join('')}

  <div class="grand-totals">
    <h3 style="margin-top:0; border-bottom:1px solid #ddd; padding-bottom:5px;">Resumen Consolidado (Solo Aprobados)</h3>
    <div class="totals-grid">
      <div class="total-item">
        <strong>Ventas Totales Aprobadas:</strong> ${formatCurrency(grandTotalSales)}
      </div>
      <div class="total-item">
        <strong>Total Comisiones a Pagar:</strong> ${formatCurrency(grandTotalPayout)}
      </div>
    </div>
  </div>

  <div class="signatures">
    <div>
      <div style="height: 50px;"></div>
      <div class="signature-line">Firma Director Comercial</div>
    </div>
    <div>
      <div style="height: 50px;"></div>
      <div class="signature-line">Firma Auditor Financiero</div>
    </div>
  </div>

  <script>
    // Optionally trigger print on load if requested
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('autoprint') === 'true') {
      window.onload = function() {
        window.print();
      }
    }
  </script>
</body>
</html>
    `;

    return new Response(htmlContent, {
      headers: { 'Content-Type': 'text/html' }
    });

  } catch (err: any) {
    console.error('Failed to generate PDF export HTML view:', err);
    return new Response('<h1>Internal Server Error</h1>', { status: 500 });
  }
}, ['admin', 'director', 'analyst']);
