import { renderToStaticMarkup } from 'react-dom/server';

import type { Invoice } from './invoice.js';

function InvoiceDocument({ invoice }: { invoice: Invoice }) {
  const total = invoice.lines.reduce(
    (sum, line) => sum + line.quantity * line.unitPrice,
    0,
  );

  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <link rel="stylesheet" href="/styles/invoice.css" />
      </head>
      <body>
        <header className="invoice-header">
          <img src="/images/logo.svg" alt="Acme" />
          <div>
            <span>Invoice</span>
            <h1>{invoice.number}</h1>
          </div>
        </header>
        <p>Bill to: {invoice.customer.name}</p>
        <table>
          <tbody>
            {invoice.lines.map((line) => (
              <tr key={line.description}>
                <td>{line.description}</td>
                <td>{line.quantity}</td>
                <td>${line.quantity * line.unitPrice}</td>
              </tr>
            ))}
          </tbody>
        </table>
        <strong>Total: ${total}</strong>
      </body>
    </html>
  );
}

export function renderReactInvoice(invoice: Invoice): string {
  return `<!doctype html>${renderToStaticMarkup(
    <InvoiceDocument invoice={invoice} />,
  )}`;
}
