import { formatFaNumber, formatOptionalDate, formatPrice } from "@/helpers/func";
import type { Order } from "../types/Types";
import { printHtmlDocument } from "@/shared/print/printHtmlDocument";

const baseReceiptStyles = `
  * { box-sizing: border-box; }
  html, body {
    margin: 0;
    padding: 0;
    font-family: Tahoma, Arial, sans-serif;
    direction: rtl;
    background: #fff;
    color: #111;
  }
  @page {
    size: 80mm auto;
    margin: 4mm;
  }
  .receipt {
    width: 100%;
    font-size: 12px;
    line-height: 1.8;
  }
  .center { text-align: center; }
  .title {
    font-size: 15px;
    font-weight: 700;
    margin-bottom: 4px;
  }
  .sub { color: #555; font-size: 11px; }
  .divider {
    border-top: 1px dashed #888;
    margin: 8px 0;
  }
  .row {
    display: flex;
    justify-content: space-between;
    gap: 8px;
  }
  .muted { color: #666; }
  .items {
    width: 100%;
    border-collapse: collapse;
    margin-top: 6px;
  }
  .items td {
    vertical-align: top;
    padding: 2px 0;
  }
  .item-name { width: 46%; }
  .item-qty { width: 18%; text-align: center; }
  .item-unit { width: 36%; text-align: left; }
  .total-row {
    font-size: 13px;
    font-weight: 700;
  }
`;

const getCustomerName = (order: Order): string => {
  const fullName = [order.user?.firstName, order.user?.lastName].filter(Boolean).join(" ").trim();
  return fullName || "-";
};

const buildOrderReceiptHtml = (order: Order): string => {
  const customerAddress = order.userAddress
    ? `${order.userAddress.province || ""}، ${order.userAddress.city || ""}، ${order.userAddress.address || ""}، کد پستی: ${order.userAddress.postalCode || "-"}`.trim()
    : "";

  const itemsHtml = order.items
    .map(
      (item) => `
      <tr>
        <td class="item-name">${item.food?.title || "-"}</td>
        <td class="item-qty">${formatFaNumber(item.quantity)}</td>
        <td class="item-unit">${formatPrice(item.unitPrice)}</td>
      </tr>
    `
    )
    .join("");

  return `
    <main class="receipt">
      <section class="center">
        <div class="title">${order.restaurant?.name || "رسید سفارش"}</div>
        <div class="sub">سفارش شماره ${formatFaNumber(order.orderNumber)}</div>
        <div class="sub">${formatOptionalDate(order.createdAt, {
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
          hour: "2-digit",
          minute: "2-digit",
        })}</div>
      </section>

      <div class="divider"></div>

      <section>
        <div class="row"><span class="muted">مشتری</span><span>${getCustomerName(order)}</span></div>
        <div class="row"><span class="muted">موبایل</span><span>${order.user?.phone || "-"}</span></div>
        <div class="row"><span class="muted">روش تحویل</span><span>${order.deliveryMethod?.description || "-"}</span></div>
        <div class="row"><span class="muted">روش پرداخت</span><span>${order.paymentMethod?.description || "-"}</span></div>
        ${
          customerAddress
            ? `<div class="divider"></div><div><span class="muted">آدرس مشتری</span><div>${customerAddress}</div></div>`
            : ""
        }
      </section>

      <div class="divider"></div>

      <section>
        <table class="items">
          <tbody>
            ${itemsHtml}
          </tbody>
        </table>
      </section>

      <div class="divider"></div>

      <section>
        <div class="row"><span class="muted">جمع آیتم‌ها</span><span>${formatPrice(order.subTotal)}</span></div>
        ${
          order.itemsDiscount > 0
            ? `<div class="row"><span class="muted">تخفیف آیتم‌ها</span><span>${formatPrice(order.itemsDiscount)}</span></div>`
            : ""
        }
        ${
          order.couponDiscount > 0
            ? `<div class="row"><span class="muted">تخفیف کوپن</span><span>${formatPrice(order.couponDiscount)}</span></div>`
            : ""
        }
        <div class="row"><span class="muted">هزینه ارسال</span><span>${formatPrice(order.deliveryFee)}</span></div>
        ${
          order.tax > 0
            ? `<div class="row"><span class="muted">مالیات</span><span>${formatPrice(order.tax)}</span></div>`
            : ""
        }
        <div class="divider"></div>
        <div class="row total-row"><span>مبلغ کل</span><span>${formatPrice(order.total)}</span></div>
      </section>

      ${
        order.description
          ? `<div class="divider"></div><section><div class="muted">توضیحات:</div><div>${order.description}</div></section>`
          : ""
      }
    </main>
  `;
};

export const printOrderReceipt = (order: Order): void => {
  const html = buildOrderReceiptHtml(order);
  printHtmlDocument({
    title: `سفارش ${order.orderNumber}`,
    html,
    widthMm: 80,
    styles: baseReceiptStyles,
  });
};
