import { useRef } from "react";
import { useLanguage } from "@/hooks/use-language";
import { supabase } from "@/integrations/supabase/client";

type ReceiptItem = {
  name: string;
  code: string;
  quantity: number;
  unit?: string;
  unitPrice: number;
  discount: number;
};

type ReceiptData = {
  invoiceNo: string;
  date: string;
  customer: string;
  phone: string;
  address: string;
  saleMan: string;
  items: ReceiptItem[];
  subTotal: number;
  discount: number;
  expense: number;
  grandTotal: number;
  paid: number;
  due: number;
  billStatus?: "rough" | "final";
};

export function useReceiptPrint() {
  const { lang } = useLanguage();

  const esc = (s: string) =>
    s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');

  const printReceipt = async (data: ReceiptData) => {
    const isBn = lang === "bn";
    const { data: settings } = await supabase
      .from("business_settings")
      .select("setting_key, setting_value")
      .in("setting_key", ["invoice_footer_terms", "invoice_footer_thanks", "company_logo_url"]);
    const sMap = new Map((settings || []).map((s: any) => [s.setting_key, s.setting_value]));
    const footerTerms = (sMap.get("invoice_footer_terms") as string) || "";
    const footerThanks = (sMap.get("invoice_footer_thanks") as string) || "";
    const logoUrl = (sMap.get("company_logo_url") as string) || "/niyamah-logo.jpg";

    const itemRows = data.items
      .map(
        (item, i) => `
      <tr>
        <td style="padding:6px 8px;border-bottom:1px solid #e5e7eb;">${i + 1}</td>
        <td style="padding:6px 8px;border-bottom:1px solid #e5e7eb;">${esc(item.name)}</td>
        <td style="padding:6px 8px;border-bottom:1px solid #e5e7eb;text-align:center;">${item.quantity}${item.unit ? ` ${esc(item.unit)}` : ""}</td>
        <td style="padding:6px 8px;border-bottom:1px solid #e5e7eb;text-align:right;">৳${item.unitPrice}</td>
        <td style="padding:6px 8px;border-bottom:1px solid #e5e7eb;text-align:right;">৳${item.discount}</td>
        <td style="padding:6px 8px;border-bottom:1px solid #e5e7eb;text-align:right;font-weight:600;">৳${item.unitPrice * item.quantity - item.discount}</td>
      </tr>`
      )
      .join("");

    const itemRowsCompact = data.items
      .map(
        (item, i) => `
      <tr>
        <td style="border:1px solid #000;padding:2px 4px;text-align:center;">${i + 1}</td>
        <td style="border:1px solid #000;padding:2px 4px;">${esc(item.name)}</td>
        <td style="border:1px solid #000;padding:2px 4px;text-align:center;">${item.quantity}${item.unit ? ` ${esc(item.unit)}` : ""}</td>
        <td style="border:1px solid #000;padding:2px 4px;text-align:right;">${item.unitPrice}</td>
        <td style="border:1px solid #000;padding:2px 4px;text-align:right;">${item.discount}</td>
        <td style="border:1px solid #000;padding:2px 4px;text-align:right;">${item.unitPrice * item.quantity - item.discount}</td>
      </tr>`
      )
      .join("");

    const isRough = data.billStatus === "rough";
    const stamp = isRough
      ? { label: "ROUGH BILL", color: "#dc2626" }
      : data.due <= 0 && data.grandTotal > 0
      ? { label: "PAID", color: "#16a34a" }
      : data.paid > 0 && data.due > 0
      ? { label: "PARTIAL PAID", color: "#ca8a04" }
      : { label: "DUE", color: "#dc2626" };

    const html = `
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>${isBn ? "বিক্রয় রসিদ" : "Sales Receipt"} — ${data.invoiceNo}</title>
  <style>
    * { margin:0; padding:0; box-sizing:border-box; }
    body { font-family: Arial, 'Noto Sans Bengali', sans-serif; color:#000; background:#fff; padding:8px; }
    .invoice { width:5.5in; font-family:Arial, 'Noto Sans Bengali', sans-serif; border:1px solid #000; padding:6px; box-sizing:border-box; margin:0 auto; }
    .banner { width:100%; height:auto; display:block; margin-bottom:6px; }
    .row { display:flex; justify-content:space-between; font-size:12px; margin-top:3px; }
    .name { font-size:13px; font-weight:bold; }
    .spacer { height:5px; }
    table { width:100%; border-collapse:collapse; font-size:11px; }
    th { border:1px solid #000; padding:2px 4px; background:#f0f0f0; }
    .summary { font-size:12px; }
    .summary .line { display:flex; justify-content:space-between; padding:1px 0; }
    .summary .line.bold { font-weight:bold; border-top:1px solid #000; padding-top:3px; margin-top:3px; }
    @page { size: 5.5in auto; margin: 0; }
    @media print { body { padding:0; } .invoice { border:none; } .stamp { -webkit-print-color-adjust: exact; print-color-adjust: exact; } }
    .invoice { position: relative; }
    .stamp {
      position: absolute; top: 45%; left: 50%;
      transform: translate(-50%, -50%) rotate(-25deg);
      border: 4px solid ${stamp.color};
      color: ${stamp.color};
      font-weight: 900; letter-spacing: 4px; font-size: 38px;
      padding: 6px 18px; opacity: 0.22; pointer-events: none;
      white-space: nowrap; z-index: 50;
    }
  </style>
</head>
<body>
  <div class="invoice">
    <div class="stamp">${stamp.label}</div>
    <img src="/niyamah-banner.jpg" alt="Niyamah Electric & Hardware" class="banner" />

    <div class="row" style="border-bottom:1px solid #000; padding-bottom:2px;">
      <span>${isBn ? "নাম" : "Name"}: ${esc(data.customer || "")}</span>
    </div>
    <div class="row" style="border-bottom:1px solid #000; padding-bottom:2px; margin-top:3px;">
      <span>${isBn ? "ঠিকানা" : "Address"}: ${esc(data.address || "")}</span>
      <span>${isBn ? "মোবাইল" : "Mobile"}: ${esc(data.phone || "")}</span>
    </div>
    <div class="row" style="border-bottom:1px solid #000; padding-bottom:2px; margin-top:3px;">
      <span>INV No: ${esc(data.invoiceNo)}</span>
      <span>${isBn ? "তারিখ" : "Date"}: ${esc(data.date)}</span>
    </div>
    <div class="spacer"></div>

    <table>
      <thead>
        <tr>
          <th style="width:8%;">No</th>
          <th>${isBn ? "পণ্যের বিবরণ" : "Item Description"}</th>
          <th style="width:10%;">Qty</th>
          <th style="width:14%;">${isBn ? "মূল্য" : "Price"}</th>
          <th style="width:14%;">${isBn ? "ডিসকাউন্ট" : "Discount"}</th>
          <th style="width:16%;">${isBn ? "পরিমাণ" : "Amount"}</th>
        </tr>
      </thead>
      <tbody>
        ${itemRowsCompact}
      </tbody>
    </table>

    <div class="spacer"></div>

    <div class="spacer"></div>


    <div class="summary" style="margin-left:auto; width:55%;">
      <div class="line"><span>${isBn ? "মোট ডিসকাউন্ট" : "Total Discount"}:</span><span>${data.discount.toFixed(0)}</span></div>
      <div class="line"><span>${isBn ? "মোট" : "Total"}:</span><span>${data.subTotal.toFixed(0)}</span></div>
      <div class="line"><span>${isBn ? "পূর্বের বকেয়া" : "Previous Due"}:</span><span>${(data.expense || 0).toFixed(0)}</span></div>
      <div class="line"><span>${isBn ? "সাব টোটাল" : "Sub Total"}:</span><span>${data.grandTotal.toFixed(0)}</span></div>
      <div class="line"><span>${isBn ? "পরিশোধিত" : "Paid"}:</span><span>${data.paid.toFixed(0)}</span></div>
      <div class="line bold"><span>${isBn ? "ব্যালেন্স / বকেয়া" : "Balance / Due"}:</span><span>${data.due.toFixed(0)}</span></div>
    </div>

    <div style="margin-top:8px; font-size:12px; font-weight:bold;">
      ${isBn ? "বিক্রয় প্রতিনিধি" : "Sales Representative"}: ${esc(data.saleMan || "")}
    </div>
    ${footerTerms || footerThanks ? `
    <div style="margin-top:10px; padding-top:6px; border-top:1px dashed #000; text-align:center; font-size:10px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">
      ${[footerTerms, footerThanks].filter(Boolean).map(esc).join(" — ")}
    </div>` : ""}
  </div>

  <script>window.onload = function() { setTimeout(function(){ window.print(); }, 200); }</script>
</body>
</html>`;

    const printWindow = window.open("", "_blank");
    if (printWindow) {
      printWindow.document.write(html);
      printWindow.document.close();
    }
  };

  return { printReceipt };
}

export type { ReceiptData, ReceiptItem };
