import { formatPaise, formatDate } from "@/lib/format";
import { SITE } from "@/lib/site";
import PrintButton from "@/components/admin/PrintButton";

type OrderForInvoice = {
  orderNumber: string;
  customerName: string;
  email: string;
  phone: string;
  addressLine1: string;
  addressLine2: string | null;
  city: string;
  state: string;
  pincode: string;
  createdAt: Date;
  subtotal: number;
  discountAmount: number;
  shippingFee: number;
  total: number;
  items: {
    id: string;
    quantity: number;
    unitPrice: number;
    lineTotal: number;
    personalization: string | null;
    product: { name: string };
    variant: { name: string } | null;
  }[];
};

type Company = { legalName: string | null; gstin: string | null; addressLine1: string | null; addressLine2: string | null; city: string | null; state: string | null; pincode: string | null } | null;
type Tax = { gstRatePercent: number; pricesIncludeTax: boolean } | null;

export default function InvoiceDocument({ order, invoiceNumber, company, tax }: { order: OrderForInvoice; invoiceNumber: string; company: Company; tax: Tax }) {
  const fromAddress = company?.addressLine1
    ? [company.addressLine1, company.addressLine2, [company.city, company.state, company.pincode].filter(Boolean).join(" ")]
        .filter(Boolean)
        .join(", ")
    : SITE.addressLines.join(", ");
  const rate = tax?.gstRatePercent ?? 0;
  const inclusive = tax?.pricesIncludeTax ?? true;
  const taxableValue = rate === 0 ? order.total : inclusive ? Math.round(order.total / (1 + rate / 100)) : order.total;
  const taxAmount = rate === 0 ? 0 : inclusive ? order.total - taxableValue : Math.round(order.total * (rate / 100));
  const grandTotal = inclusive ? order.total : order.total + taxAmount;

  return (
    <div className="mx-auto max-w-2xl">
      <div className="mb-4 flex justify-end print:hidden">
        <PrintButton />
      </div>

      <div className="rounded-lg border border-rose-100 bg-white p-8 print:border-0 print:p-0">
        <div className="flex items-start justify-between border-b border-stone-200 pb-4">
          <div>
            <div className="flex items-center gap-2">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src="/brand/logo.png" alt="" width={36} height={36} className="h-9 w-9" />
              <h1 className="font-[family-name:var(--font-heading)] text-xl font-bold text-stone-800">
                {company?.legalName || SITE.name}
              </h1>
            </div>
            {company?.gstin && <p className="mt-1 text-xs text-stone-500">GSTIN: {company.gstin}</p>}
            {fromAddress && <p className="mt-1 text-xs text-stone-500">{fromAddress}</p>}
            <p className="mt-1 text-xs text-stone-500">{SITE.email}</p>
          </div>
          <div className="text-right">
            <p className="text-lg font-bold text-rose-700">TAX INVOICE</p>
            <p className="mt-1 text-xs text-stone-500">Invoice #: {invoiceNumber}</p>
            <p className="text-xs text-stone-500">Order #: {order.orderNumber}</p>
            <p className="text-xs text-stone-500">Date: {formatDate(order.createdAt)}</p>
          </div>
        </div>

        <div className="mt-4">
          <p className="text-xs font-semibold uppercase text-stone-500">Bill to</p>
          <p className="mt-1 text-sm font-medium text-stone-800">{order.customerName}</p>
          <p className="text-xs text-stone-500">
            {order.addressLine1}
            {order.addressLine2 ? `, ${order.addressLine2}` : ""}, {order.city}, {order.state} {order.pincode}
          </p>
          <p className="text-xs text-stone-500">{order.phone} · {order.email}</p>
        </div>

        <table className="mt-6 w-full text-sm">
          <thead className="border-b border-stone-200 text-left text-xs uppercase text-stone-500">
            <tr>
              <th className="pb-2">Item</th>
              <th className="pb-2 text-right">Qty</th>
              <th className="pb-2 text-right">Unit price</th>
              <th className="pb-2 text-right">Amount</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-stone-100">
            {order.items.map((item) => (
              <tr key={item.id}>
                <td className="py-2 text-stone-700">
                  {item.product.name}
                  {item.variant ? ` (${item.variant.name})` : ""}
                  {item.personalization ? ` — "${item.personalization}"` : ""}
                </td>
                <td className="py-2 text-right text-stone-600">{item.quantity}</td>
                <td className="py-2 text-right text-stone-600">{formatPaise(item.unitPrice)}</td>
                <td className="py-2 text-right text-stone-800">{formatPaise(item.lineTotal)}</td>
              </tr>
            ))}
          </tbody>
        </table>

        <div className="mt-4 ml-auto max-w-xs space-y-1 text-sm">
          <div className="flex justify-between text-stone-500">
            <span>Subtotal</span>
            <span>{formatPaise(order.subtotal)}</span>
          </div>
          {order.discountAmount > 0 && (
            <div className="flex justify-between text-stone-500">
              <span>Discount</span>
              <span>−{formatPaise(order.discountAmount)}</span>
            </div>
          )}
          <div className="flex justify-between text-stone-500">
            <span>Shipping</span>
            <span>{formatPaise(order.shippingFee)}</span>
          </div>
          {rate > 0 && (
            <>
              <div className="flex justify-between border-t border-stone-200 pt-1 text-stone-500">
                <span>Taxable value</span>
                <span>{formatPaise(taxableValue)}</span>
              </div>
              <div className="flex justify-between text-stone-500">
                <span>GST ({rate}%)</span>
                <span>{formatPaise(taxAmount)}</span>
              </div>
            </>
          )}
          <div className="flex justify-between border-t border-stone-200 pt-1 text-base font-semibold text-stone-800">
            <span>Total</span>
            <span>{formatPaise(grandTotal)}</span>
          </div>
        </div>

        <p className="mt-8 text-center text-xs text-stone-400">Thank you for shopping with {SITE.name}.</p>
      </div>
    </div>
  );
}
