import { NextRequest, NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';
export const maxDuration = 60;

interface LineItem {
  description: string;
  quantity: number;
  rate: number;
}

interface InvoiceData {
  invoiceNumber: string;
  date: string;
  dueDate: string;
  from: { name: string; address: string; email: string };
  to: { name: string; company: string; address: string; email: string };
  items: LineItem[];
  taxRate: number;
  discount: number;
  notes: string;
  currency: string;
}

function buildInvoiceHTML(data: InvoiceData): string {
  const safeItems = (data.items || []).map(i => ({
    description: i.description || '',
    quantity: Number(i.quantity) || 0,
    rate: Number(i.rate) || 0,
  }));
  const subtotal = safeItems.reduce((sum, item) => sum + item.quantity * item.rate, 0);
  const discountPct = Number(data.discount) || 0;
  const taxPct = Number(data.taxRate) || 0;
  const discountAmount = subtotal * (discountPct / 100);
  const afterDiscount = subtotal - discountAmount;
  const taxAmount = afterDiscount * (taxPct / 100);
  const total = afterDiscount + taxAmount;
  const sym = data.currency === 'EUR' ? '\u20ac' : data.currency === 'GBP' ? '\u00a3' : '$';

  const fmt = (n: number) => `${sym}${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;

  return `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body { font-family: 'Segoe UI', system-ui, -apple-system, sans-serif; color: #1a1a2e; background: #fff; padding: 48px; max-width: 800px; margin: 0 auto; }
  .header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 48px; }
  .brand { font-size: 28px; font-weight: 700; color: #0C1222; letter-spacing: -0.5px; }
  .brand-sub { font-size: 11px; color: #94a3b8; margin-top: 4px; letter-spacing: 1px; text-transform: uppercase; }
  .invoice-meta { text-align: right; }
  .invoice-number { font-size: 14px; color: #64748b; margin-bottom: 4px; }
  .invoice-number strong { color: #0C1222; font-size: 18px; display: block; }
  .date-row { font-size: 12px; color: #94a3b8; margin-top: 2px; }
  .parties { display: flex; gap: 48px; margin-bottom: 40px; }
  .party { flex: 1; }
  .party-label { font-size: 10px; text-transform: uppercase; letter-spacing: 1.5px; color: #0EA5E9; font-weight: 600; margin-bottom: 8px; }
  .party-name { font-size: 15px; font-weight: 600; color: #0C1222; }
  .party-detail { font-size: 12px; color: #64748b; line-height: 1.6; margin-top: 4px; }
  table { width: 100%; border-collapse: collapse; margin-bottom: 32px; }
  thead th { font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: #94a3b8; padding: 12px 16px; text-align: left; border-bottom: 2px solid #e2e8f0; }
  thead th:last-child, thead th:nth-child(3), thead th:nth-child(2) { text-align: right; }
  tbody td { padding: 14px 16px; font-size: 13px; color: #334155; border-bottom: 1px solid #f1f5f9; }
  tbody td:last-child, tbody td:nth-child(3), tbody td:nth-child(2) { text-align: right; font-variant-numeric: tabular-nums; }
  .totals { display: flex; justify-content: flex-end; margin-bottom: 40px; }
  .totals-table { width: 280px; }
  .totals-row { display: flex; justify-content: space-between; padding: 8px 0; font-size: 13px; color: #64748b; }
  .totals-row.total { border-top: 2px solid #0C1222; margin-top: 8px; padding-top: 12px; font-size: 18px; font-weight: 700; color: #0C1222; }
  .notes { padding: 20px; background: #f8fafc; border-radius: 8px; font-size: 12px; color: #64748b; line-height: 1.6; }
  .notes-label { font-size: 10px; text-transform: uppercase; letter-spacing: 1.5px; color: #0EA5E9; font-weight: 600; margin-bottom: 8px; }
  .footer { margin-top: 48px; padding-top: 24px; border-top: 1px solid #e2e8f0; text-align: center; font-size: 11px; color: #94a3b8; }
</style>
</head>
<body>
  <div class="header">
    <div>
      <div class="brand">${escapeHtml(data.from.name)}</div>
      <div class="brand-sub">Invoice</div>
    </div>
    <div class="invoice-meta">
      <div class="invoice-number">Invoice <strong>#${escapeHtml(data.invoiceNumber)}</strong></div>
      <div class="date-row">Issued: ${escapeHtml(data.date)}</div>
      <div class="date-row">Due: ${escapeHtml(data.dueDate)}</div>
    </div>
  </div>

  <div class="parties">
    <div class="party">
      <div class="party-label">From</div>
      <div class="party-name">${escapeHtml(data.from.name)}</div>
      <div class="party-detail">${escapeHtml(data.from.address).replace(/\n/g, '<br>')}</div>
      <div class="party-detail">${escapeHtml(data.from.email)}</div>
    </div>
    <div class="party">
      <div class="party-label">Bill To</div>
      <div class="party-name">${escapeHtml(data.to.company || data.to.name)}</div>
      ${data.to.company ? `<div class="party-detail">${escapeHtml(data.to.name)}</div>` : ''}
      <div class="party-detail">${escapeHtml(data.to.address).replace(/\n/g, '<br>')}</div>
      <div class="party-detail">${escapeHtml(data.to.email)}</div>
    </div>
  </div>

  <table>
    <thead>
      <tr><th>Description</th><th>Qty</th><th>Rate</th><th>Amount</th></tr>
    </thead>
    <tbody>
      ${safeItems.map(item => `
        <tr>
          <td>${escapeHtml(item.description)}</td>
          <td>${item.quantity}</td>
          <td>${fmt(item.rate)}</td>
          <td>${fmt(item.quantity * item.rate)}</td>
        </tr>
      `).join('')}
    </tbody>
  </table>

  <div class="totals">
    <div class="totals-table">
      <div class="totals-row"><span>Subtotal</span><span>${fmt(subtotal)}</span></div>
      ${discountPct > 0 ? `<div class="totals-row"><span>Discount (${discountPct}%)</span><span>-${fmt(discountAmount)}</span></div>` : ''}
      ${taxPct > 0 ? `<div class="totals-row"><span>Tax (${taxPct}%)</span><span>${fmt(taxAmount)}</span></div>` : ''}
      <div class="totals-row total"><span>Total</span><span>${fmt(total)}</span></div>
    </div>
  </div>

  ${data.notes ? `
  <div class="notes">
    <div class="notes-label">Notes</div>
    ${escapeHtml(data.notes)}
  </div>
  ` : ''}

  <div class="footer">
    Generated by InvoiceForge \u2014 The Hearth Showcase \u2022 spookysoftwaresyndicate.com/demos/invoice-forge
  </div>
</body>
</html>`;
}

function escapeHtml(str: string | undefined | null): string {
  if (!str) return '';
  return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

export async function POST(request: NextRequest) {
  try {
    const invoiceData: InvoiceData = await request.json();

    if (!invoiceData.items || invoiceData.items.length === 0) {
      return NextResponse.json({ error: 'At least one line item is required.' }, { status: 400 });
    }

    const htmlContent = buildInvoiceHTML(invoiceData);

    // Step 1: Create PDF generation request
    const createResponse = await fetch('https://apps.abacus.ai/api/createConvertHtmlToPdfRequest', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        deployment_token: process.env.ABACUSAI_API_KEY,
        html_content: htmlContent,
        pdf_options: {
          format: 'A4',
          margin: { top: '0mm', right: '0mm', bottom: '0mm', left: '0mm' },
          print_background: true,
        },
      }),
    });

    if (!createResponse.ok) {
      console.error('PDF create error:', await createResponse.text());
      return NextResponse.json({ error: 'PDF service unavailable.' }, { status: 502 });
    }

    const { request_id } = await createResponse.json();
    if (!request_id) {
      return NextResponse.json({ error: 'No request ID returned.' }, { status: 500 });
    }

    // Step 2: Poll for completion
    const maxAttempts = 60;
    let attempts = 0;

    while (attempts < maxAttempts) {
      await new Promise(resolve => setTimeout(resolve, 1500));

      const statusResponse = await fetch('https://apps.abacus.ai/api/getConvertHtmlToPdfStatus', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          request_id,
          deployment_token: process.env.ABACUSAI_API_KEY,
        }),
      });

      const statusResult = await statusResponse.json();
      const status = statusResult?.status || 'FAILED';

      if (status === 'SUCCESS') {
        const result = statusResult?.result;
        if (result?.result) {
          const pdfBuffer = Buffer.from(result.result, 'base64');
          return new NextResponse(pdfBuffer, {
            headers: {
              'Content-Type': 'application/pdf',
              'Content-Disposition': `attachment; filename="invoice-${invoiceData.invoiceNumber}.pdf"`,
            },
          });
        }
        return NextResponse.json({ error: 'PDF generated but no data returned.' }, { status: 500 });
      }

      if (status === 'FAILED') {
        return NextResponse.json({ error: 'PDF generation failed.' }, { status: 500 });
      }

      attempts++;
    }

    return NextResponse.json({ error: 'PDF generation timed out.' }, { status: 504 });
  } catch (error) {
    console.error('InvoiceForge error:', error);
    return NextResponse.json({ error: 'Failed to generate invoice.' }, { status: 500 });
  }
}