import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'

export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const invoice = await prisma.invoice.findUnique({
      where: { id },
      include: {
        client: true,
        items: {
          include: {
            product: true,
          },
        },
      },
    })

    if (!invoice) {
      return NextResponse.json({ error: 'Invoice not found' }, { status: 404 })
    }

    const storeSettings = await prisma.settings.findUnique({
      where: { id: 'default' },
    })

    const html = generateInvoiceHTML(invoice, storeSettings)
    
    return new NextResponse(html, {
      headers: {
        'Content-Type': 'text/html',
      },
    })
  } catch (error) {
    console.error('Error generating invoice:', error)
    return NextResponse.json({ error: 'Failed to generate invoice' }, { status: 500 })
  }
}

function generateInvoiceHTML(invoice: any, settings: any) {
  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('fr-MA', { 
      style: 'currency', 
      currency: 'MAD' 
    }).format(amount)
  }

  const formatDate = (date: Date) => {
    return new Date(date).toLocaleDateString('fr-MA', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    })
  }

  const subtotal = invoice.items.reduce((sum: number, item: any) => sum + Number(item.total), 0)
  const tax = Number(invoice.tax)
  const discount = Number(invoice.discount)
  const total = Number(invoice.total)
  const paid = Number(invoice.paidAmount)
  const remaining = total - paid

  const itemsHTML = invoice.items.map((item: any, index: number) => `
    <tr>
      <td style="padding: 12px; border-bottom: 1px solid #e2e8f0;">${index + 1}</td>
      <td style="padding: 12px; border-bottom: 1px solid #e2e8f0;">${item.product.sku}</td>
      <td style="padding: 12px; border-bottom: 1px solid #e2e8f0;">${item.product.name}</td>
      <td style="padding: 12px; border-bottom: 1px solid #e2e8f0; text-align: center;">${item.quantity}</td>
      <td style="padding: 12px; border-bottom: 1px solid #e2e8f0; text-align: right;">${formatCurrency(Number(item.unitPrice))}</td>
      <td style="padding: 12px; border-bottom: 1px solid #e2e8f0; text-align: right;">${formatCurrency(Number(item.total))}</td>
    </tr>
  `).join('')

  return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Facture ${invoice.invoiceNumber}</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font-family: 'Helvetica Neue', Arial, sans-serif; color: #1a202c; line-height: 1.5; }
    .invoice-container { max-width: 800px; margin: 0 auto; padding: 40px; }
    .header { display: flex; justify-content: space-between; margin-bottom: 40px; }
    .company-info h1 { color: #0d9488; font-size: 28px; margin-bottom: 8px; }
    .company-info p { color: #64748b; font-size: 14px; }
    .invoice-title { text-align: right; }
    .invoice-title h2 { font-size: 32px; color: #0d9488; margin-bottom: 8px; }
    .invoice-title p { color: #64748b; }
    .invoice-box { border: 1px solid #e2e8f0; border-radius: 8px; overflow: hidden; }
    .info-section { display: flex; border-bottom: 1px solid #e2e8f0; }
    .info-box { flex: 1; padding: 20px; }
    .info-box:first-child { border-right: 1px solid #e2e8f0; }
    .info-box h3 { font-size: 12px; color: #64748b; text-transform: uppercase; margin-bottom: 8px; }
    .info-box p { font-size: 14px; }
    .info-box .status { 
      display: inline-block; 
      padding: 4px 12px; 
      border-radius: 9999px; 
      font-size: 12px; 
      font-weight: 600;
    }
    .status-paid { background: #d1fae5; color: #065f46; }
    .status-pending { background: #fef3c7; color: #92400e; }
    table { width: 100%; border-collapse: collapse; }
    th { background: #f8fafc; padding: 12px; text-align: left; font-size: 12px; color: #64748b; text-transform: uppercase; }
    .text-right { text-align: right; }
    .text-center { text-align: center; }
    .totals { padding: 20px; background: #f8fafc; }
    .totals-row { display: flex; justify-content: flex-end; gap: 60px; padding: 4px 0; }
    .totals-row.final { font-size: 18px; font-weight: 700; color: #0d9488; padding-top: 8px; border-top: 2px solid #0d9488; margin-top: 8px; }
    .footer { margin-top: 40px; text-align: center; color: #64748b; font-size: 12px; }
    @media print {
      @page { margin: 0; size: auto; }
      body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
      html, body { margin: 0; padding: 0; }
      .invoice-container { margin: 0; padding: 20px; }
    }
  </style>
</head>
<body>
  <div class="invoice-container">
    <div class="header">
      <div class="company-info">
        <h1>${settings?.storeName || 'OptiCare'}</h1>
        <p>${settings?.address || ''}</p>
        <p>${settings?.phone || ''}</p>
        <p>${settings?.email || ''}</p>
      </div>
      <div class="invoice-title">
        <h2>FACTURE</h2>
        <p><strong>N°:</strong> ${invoice.invoiceNumber}</p>
        <p><strong>Date:</strong> ${formatDate(invoice.createdAt)}</p>
      </div>
    </div>

    <div class="invoice-box">
      <div class="info-section">
        <div class="info-box">
          <h3>Client</h3>
          <p><strong>${invoice.client?.name || 'Client anonoyme'}</strong></p>
          <p>${invoice.client?.phone || ''}</p>
          <p>${invoice.client?.email || ''}</p>
          <p>${invoice.client?.address || ''}</p>
        </div>
        <div class="info-box">
          <h3>Informations</h3>
          <p><strong>Mode de paiement:</strong> ${invoice.paymentMethod || '-'}</p>
          <p><strong>Statut:</strong> 
            <span class="status ${invoice.status === 'PAID' ? 'status-paid' : 'status-pending'}">
              ${invoice.status === 'PAID' ? 'PAYÉE' : 'EN ATTENTE'}
            </span>
          </p>
        </div>
      </div>

      <table>
        <thead>
          <tr>
            <th style="width: 50px;">#</th>
            <th style="width: 100px;">SKU</th>
            <th>Produit</th>
            <th style="width: 80px;" class="text-center">Qté</th>
            <th style="width: 120px;" class="text-right">Prix Unit.</th>
            <th style="width: 120px;" class="text-right">Total</th>
          </tr>
        </thead>
        <tbody>
          ${itemsHTML}
        </tbody>
      </table>

      <div class="totals">
        <div class="totals-row">
          <span>Sous-total:</span>
          <span>${formatCurrency(subtotal)}</span>
        </div>
        <div class="totals-row">
          <span>TVA (${settings?.defaultTva || 10}%):</span>
          <span>${formatCurrency(tax)}</span>
        </div>
        ${discount > 0 ? `
        <div class="totals-row" style="color: #dc2626;">
          <span>Remise:</span>
          <span>-${formatCurrency(discount)}</span>
        </div>
        ` : ''}
        <div class="totals-row final">
          <span>TOTAL:</span>
          <span>${formatCurrency(total)}</span>
        </div>
        ${invoice.status === 'PENDING' ? `
        <div class="totals-row" style="color: #059669;">
          <span>Montant payé:</span>
          <span>${formatCurrency(paid)}</span>
        </div>
        <div class="totals-row" style="color: #d97706;">
          <span>Reste à payer:</span>
          <span>${formatCurrency(remaining)}</span>
        </div>
        ` : ''}
      </div>
    </div>

    <div class="footer">
      <p>${settings?.invoiceFooter || 'Merci pour votre confiance!'}</p>
      <p>${settings?.storeName || 'OptiCare'} - Logiciel de gestion</p>
    </div>
  </div>
</body>
</html>
  `
}