'use client';

import { formatCurrency } from '@/lib/utils/currency';
import type { CurrencyDisplayFormat } from '@/lib/db/queries/getCurrencySettings';

interface InvoiceItem {
  product_name: string;
  sku: string;
  variant_name?: string | null;
  quantity: number;
  unit_price: number;
  total_price: number;
}

interface ReturnedItem {
  product_name: string;
  sku: string;
  variant_name?: string | null;
  quantity: number;
  total_price: number;
  return_reason?: string | null;
}

interface InvoiceData {
  invoice_number: string;
  generated_at: string;
  site: {
    name: string;
    tagline: string;
    logo: string | null;
    address: string;
    phone: string;
    email: string;
    vat_label: string;
    currency: { code: string; symbol: string; format: CurrencyDisplayFormat };
  };
  order: {
    order_number: string;
    status: string;
    created_at: string;
    payment_method: string;
    payment_status: string;
  };
  customer: {
    name: string;
    email: string;
    phone: string;
  };
  billing_address: {
    full_name: string;
    phone: string;
    address_line1: string;
    city: string;
    state: string;
    postal_code: string;
    country: string;
  } | null;
  shipping_address: {
    full_name: string;
    phone: string;
    address_line1: string;
    city: string;
    state: string;
    postal_code: string;
    country: string;
  } | null;
  items: InvoiceItem[];
  returned_items: ReturnedItem[];
  totals: {
    subtotal: number;
    coupon_discount: number;
    coupon_code: string | null;
    delivery_fee: number;
    tax_amount: number;
    tax_percentage: number;
    grand_total: number;
  };
}

interface InvoicePrintProps {
  data: InvoiceData;
}

const PAYMENT_METHOD_LABELS: Record<string, string> = {
  cod: 'Cash on Delivery',
  bank_transfer: 'Bank Transfer',
  paypal: 'PayPal',
  stripe: 'Stripe',
};

export function generateInvoiceHTML(data: InvoiceData): string {
  const { site, order, customer, billing_address, shipping_address, items, returned_items, totals } = data;

  const address = shipping_address || billing_address;
  const money = (amount: number) => formatCurrency(amount, site.currency);

  return `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Invoice ${data.invoice_number}</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #1a1a1a; padding: 40px; }
    .invoice-header { display: flex; justify-content: space-between; align-items: start; margin-bottom: 30px; border-bottom: 2px solid #2563eb; padding-bottom: 20px; }
    .company-info h1 { font-size: 24px; color: #2563eb; margin-bottom: 4px; }
    .company-info p { color: #6b7280; font-size: 13px; }
    .invoice-title { text-align: right; }
    .invoice-title h2 { font-size: 28px; color: #1e40af; text-transform: uppercase; letter-spacing: 2px; }
    .invoice-title .invoice-number { font-size: 16px; color: #374151; font-weight: 600; margin-top: 4px; }
    .invoice-title .invoice-date { font-size: 13px; color: #6b7280; }
    .info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 30px; margin-bottom: 25px; }
    .info-section h3 { font-size: 13px; text-transform: uppercase; color: #6b7280; margin-bottom: 8px; letter-spacing: 1px; }
    .info-section p { font-size: 14px; line-height: 1.6; }
    .info-section .name { font-weight: 600; }
    table { width: 100%; border-collapse: collapse; margin: 20px 0; }
    thead th { background: #f3f4f6; padding: 12px; text-align: left; font-size: 12px; text-transform: uppercase; color: #374151; letter-spacing: 0.5px; border-bottom: 2px solid #e5e7eb; }
    tbody td { padding: 12px; font-size: 14px; border-bottom: 1px solid #f3f4f6; }
    tbody tr:last-child td { border-bottom: 2px solid #e5e7eb; }
    .text-right { text-align: right; }
    .text-center { text-align: center; }
    .totals-section { margin-top: 10px; }
    .totals-section table { width: 300px; margin-left: auto; }
    .totals-section td { padding: 8px 12px; font-size: 14px; }
    .totals-section .grand-total { font-size: 18px; font-weight: 700; color: #2563eb; }
    .returned-section { margin-top: 25px; }
    .returned-section h3 { color: #dc2626; font-size: 14px; text-transform: uppercase; margin-bottom: 10px; }
    .returned-section table thead th { background: #fef2f2; color: #dc2626; }
    .returned-section .strikethrough { text-decoration: line-through; color: #9ca3af; }
    .footer { margin-top: 40px; padding-top: 20px; border-top: 1px solid #e5e7eb; text-align: center; font-size: 12px; color: #9ca3af; }
    @media print { body { padding: 20px; } }
  </style>
</head>
<body>
  <div class="invoice-header">
    <div class="company-info">
      <h1>${site.name}</h1>
      ${site.tagline ? `<p>${site.tagline}</p>` : ''}
      ${site.address ? `<p style="margin-top:8px;font-size:12px;">${site.address}</p>` : ''}
      ${site.phone ? `<p style="font-size:12px;">Phone: ${site.phone}</p>` : ''}
      ${site.email ? `<p style="font-size:12px;">Email: ${site.email}</p>` : ''}
    </div>
    <div class="invoice-title">
      <h2>Invoice</h2>
      <div class="invoice-number"># ${data.invoice_number}</div>
      <div class="invoice-date">Date: ${new Date(data.generated_at).toLocaleDateString('en-PK', { day: '2-digit', month: 'short', year: 'numeric' })}</div>
    </div>
  </div>

  <div class="info-grid">
    <div>
      <div class="info-section">
        <h3>Bill To</h3>
        <p class="name">${customer.name}</p>
        ${customer.email ? `<p>${customer.email}</p>` : ''}
        ${customer.phone ? `<p>${customer.phone}</p>` : ''}
      </div>
      ${billing_address ? `
      <div class="info-section" style="margin-top:15px;">
        <h3>Billing Address</h3>
        <p>${billing_address.address_line1}</p>
        <p>${billing_address.city}, ${billing_address.state} ${billing_address.postal_code}</p>
        <p>${billing_address.country}</p>
      </div>` : ''}
    </div>
    <div>
      <div class="info-section">
        <h3>Order Details</h3>
        <p><strong>Order #:</strong> ${order.order_number}</p>
        <p><strong>Order Date:</strong> ${new Date(order.created_at).toLocaleDateString('en-PK', { day: '2-digit', month: 'short', year: 'numeric' })}</p>
        <p><strong>Payment:</strong> ${PAYMENT_METHOD_LABELS[order.payment_method] || order.payment_method}</p>
        <p><strong>Status:</strong> ${order.payment_status.replace(/_/g, ' ')}</p>
      </div>
      ${address ? `
      <div class="info-section" style="margin-top:15px;">
        <h3>Shipping Address</h3>
        <p class="name">${address.full_name}</p>
        <p>${address.address_line1}</p>
        <p>${address.city}, ${address.state} ${address.postal_code}</p>
        <p>${address.country}</p>
      </div>` : ''}
    </div>
  </div>

  <table>
    <thead>
      <tr>
        <th>#</th>
        <th>Product</th>
        <th>SKU</th>
        <th class="text-center">Qty</th>
        <th class="text-right">Unit Price</th>
        <th class="text-right">Total</th>
      </tr>
    </thead>
    <tbody>
      ${items.map((item, index) => `
      <tr>
        <td>${index + 1}</td>
        <td>${item.product_name}${item.variant_name ? ` <br/><small style="color:#6b7280;">(${item.variant_name})</small>` : ''}</td>
        <td><small>${item.sku}</small></td>
        <td class="text-center">${item.quantity}</td>
        <td class="text-right">${money(item.unit_price)}</td>
        <td class="text-right">${money(item.total_price)}</td>
      </tr>`).join('')}
    </tbody>
  </table>

  <div class="totals-section">
    <table>
      <tr>
        <td style="color:#6b7280;">Subtotal</td>
        <td class="text-right">${money(totals.subtotal)}</td>
      </tr>
      ${totals.coupon_discount > 0 ? `
      <tr>
        <td style="color:#6b7280;">Coupon (${totals.coupon_code})</td>
        <td class="text-right" style="color:#059669;">- ${money(totals.coupon_discount)}</td>
      </tr>` : ''}
      <tr>
        <td style="color:#6b7280;">Delivery Fee</td>
        <td class="text-right">${money(totals.delivery_fee)}</td>
      </tr>
      ${totals.tax_amount > 0 ? `
      <tr>
        <td style="color:#6b7280;">${site.vat_label} (${totals.tax_percentage}%)</td>
        <td class="text-right">${money(totals.tax_amount)}</td>
      </tr>` : ''}
      <tr>
        <td colspan="2"><hr style="border-color:#e5e7eb;margin:4px 0;" /></td>
      </tr>
      <tr>
        <td class="grand-total">Grand Total</td>
        <td class="grand-total text-right">${money(totals.grand_total)}</td>
      </tr>
    </table>
  </div>

  ${returned_items.length > 0 ? `
  <div class="returned-section">
    <h3>⚠ Returned Items (Not Included in Total)</h3>
    <table>
      <thead>
        <tr>
          <th>Product</th>
          <th>Reason</th>
          <th class="text-center">Qty</th>
          <th class="text-right">Amount</th>
        </tr>
      </thead>
      <tbody>
        ${returned_items.map((item) => `
        <tr class="strikethrough">
          <td>${item.product_name}${item.variant_name ? ` (${item.variant_name})` : ''}</td>
          <td><small>${item.return_reason || 'N/A'}</small></td>
          <td class="text-center">${item.quantity}</td>
          <td class="text-right">${money(item.total_price)}</td>
        </tr>`).join('')}
      </tbody>
    </table>
  </div>` : ''}

  <div class="footer">
    <p>Thank you for shopping with ${site.name}!</p>
    <p>This is a computer-generated invoice.</p>
  </div>

  <script>
    window.onload = function() { window.print(); }
  </script>
</body>
</html>`;
}

export default function InvoicePrint({ data }: InvoicePrintProps) {
  const handlePrint = () => {
    const html = generateInvoiceHTML(data);
    const printWindow = window.open('', '_blank', 'width=900,height=700');
    if (printWindow) {
      printWindow.document.write(html);
      printWindow.document.close();
    }
  };

  return null; // This component doesn't render anything directly
}