'use client';

import { useRef, useCallback, useEffect, useState } from 'react';
import type { ReceiptData, StoreSettings } from '@/types';
import { settingsApi } from '@/lib/api';

type ReceiptType = 'customer';

// LasminiShop - customer receipt only

function formatRp(amount: number): string {
  return 'Rp ' + Math.round(amount).toLocaleString('id-ID');
}

function formatTime(isoString: string): string {
  return new Date(isoString).toLocaleString('id-ID', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

/** Escape untrusted strings before embedding into receipt HTML (print window). */
function escapeHtml(value: unknown): string {
  return String(value ?? '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

/**
 * Build receipt HTML for thermal printer (58mm / 80mm width).
 * Uses inline styles for maximum compatibility.
 */
interface StoreInfo {
  name: string;
  address: string;
  phone: string;
  receiptHeader?: string;
  receiptFooter?: string;
}

const DEFAULT_STORE: StoreInfo = {
  name: 'LASMINISHOP',
  address: 'Jl. Contoh No. 123, Jakarta',
  phone: '021-1234567',
  receiptHeader: 'Terima kasih atas pembelian Anda!',
  receiptFooter: 'Simpan struk ini sebagai bukti pembayaran',
};

function buildReceiptHTML(data: ReceiptData, type: ReceiptType, store: StoreInfo = DEFAULT_STORE): string {
  const items = data.items;

  if (items.length === 0) {
    return '';
  }

  const title = 'STRUK PEMBAYARAN';
  const showPayment = true;

  let html = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>${title}</title>
<style>
  @page { margin: 2mm; size: 80mm auto; }
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body {
    font-family: 'Courier New', Courier, monospace;
    font-size: 12px;
    line-height: 1.4;
    color: #000;
    width: 76mm;
    max-width: 76mm;
    padding: 2mm;
  }
  .center { text-align: center; }
  .right { text-align: right; }
  .bold { font-weight: bold; }
  .big { font-size: 16px; font-weight: bold; }
  .small { font-size: 10px; }
  .divider { border-top: 1px dashed #000; margin: 4px 0; }
  .double-divider { border-top: 2px solid #000; margin: 4px 0; }
  .row { display: flex; justify-content: space-between; }
  .item-name { font-weight: bold; }
  .item-detail { padding-left: 12px; font-size: 11px; }
  .item-note { padding-left: 12px; font-size: 11px; font-style: italic; }
  .station-label {
    text-align: center;
    font-size: 20px;
    font-weight: bold;
    padding: 4px 0;
    border: 2px solid #000;
    margin-bottom: 4px;
  }
  table { width: 100%; border-collapse: collapse; }
  td { vertical-align: top; padding: 1px 0; }
  .qty { width: 30px; text-align: center; }
  .price { text-align: right; white-space: nowrap; }
</style>
</head>
<body>`;

  // Customer receipt — full receipt with header (all text escaped)
  html += `
<div class="center">
  <div class="big">${escapeHtml(store.name)}</div>
  <div class="small">${escapeHtml(store.address)}</div>
  <div class="small">Telp: ${escapeHtml(store.phone)}</div>
</div>
<div class="divider"></div>
<div class="row"><span>No: ${escapeHtml(data.order_number)}</span><span>${escapeHtml(formatTime(data.created_at))}</span></div>
<div class="row"><span>Kasir: ${escapeHtml(data.cashier_name)}</span></div>
${data.customer_name ? `<div>Pelanggan: ${escapeHtml(data.customer_name)}</div>` : ''}
<div class="double-divider"></div>`;

  // Items with unit info (prefer sale unit when multi-unit)
  html += '<table>';
  items.forEach((item) => {
    const saleUnit = item.unit_name || item.unit || '';
    const saleQty = item.unit_qty != null && Number(item.unit_qty) > 0 ? Number(item.unit_qty) : item.quantity;
    const unitLabel = saleUnit ? ` ${escapeHtml(saleUnit)}` : '';
    const baseNote =
      item.unit_qty != null && item.unit_name && Number(item.quantity) !== Number(item.unit_qty)
        ? ` (=${escapeHtml(item.quantity)} ${escapeHtml(item.unit || 'pcs')})`
        : '';
    const unitPriceLabel = item.unit_price || item.product_price
      ? ` @${formatRp(item.unit_price || item.product_price)}`
      : '';
    html += `
<tr>
  <td class="qty">${escapeHtml(saleQty)}${unitLabel}</td>
  <td class="item-name">${escapeHtml(item.product_name)}${baseNote}<br><span class="small">${unitPriceLabel}</span></td>
  <td class="price">${formatRp(item.subtotal)}</td>
</tr>`;

    // Notes
    if (item.notes) {
      html += `<tr><td></td><td colspan="2" class="item-note">** ${escapeHtml(item.notes)}</td></tr>`;
    }
  });
  html += '</table>';

  if (showPayment) {
    // Payment summary
    const methodLabel = data.payment_method === 'cash' ? 'Tunai' : data.payment_method === 'transfer' ? 'Transfer' : 'QRIS';
    const statusLabel = data.payment_status === 'paid' ? 'LUNAS' : data.payment_status === 'partial' ? 'BAYAR SEBAGIAN' : 'BELUM BAYAR (TEMPO)';

    html += `
<div class="divider"></div>
<div class="row"><span>Subtotal</span><span>${formatRp(data.subtotal)}</span></div>
<div class="row"><span>PPN ${data.tax_rate ?? 11}%</span><span>${formatRp(data.tax)}</span></div>`;

    if (data.discount > 0) {
      html += `<div class="row"><span>Diskon${data.discount_label ? ` (${escapeHtml(data.discount_label)})` : ''}</span><span>-${formatRp(data.discount)}</span></div>`;
    }

    html += `
<div class="double-divider"></div>
<div class="row bold big"><span>TOTAL</span><span>${formatRp(data.total)}</span></div>
<div class="divider"></div>
<div class="row"><span>Metode</span><span>${methodLabel}</span></div>
<div class="row bold"><span>Status</span><span>${statusLabel}</span></div>`;

    if (data.paid_amount && data.paid_amount > 0 && data.payment_status !== 'paid') {
      html += `<div class="row"><span>Dibayar</span><span>${formatRp(data.paid_amount)}</span></div>`;
      html += `<div class="row bold"><span>Sisa</span><span>${formatRp(data.total - data.paid_amount)}</span></div>`;
    }

    if (data.due_date) {
      html += `<div class="row"><span>Jatuh Tempo</span><span>${escapeHtml(data.due_date)}</span></div>`;
    }

    if (data.cash_received && data.cash_received > 0 && data.payment_status === 'paid') {
      html += `<div class="row"><span>Tunai</span><span>${formatRp(data.cash_received)}</span></div>`;
      if (data.cash_change && data.cash_change > 0) {
        html += `<div class="row bold"><span>Kembalian</span><span>${formatRp(data.cash_change)}</span></div>`;
      }
    }

    html += `
<div class="divider"></div>
<div class="center small" style="margin-top:6px">
  ${escapeHtml(store.receiptHeader || 'Terima kasih atas pembelian Anda!')}<br>
  ${escapeHtml(store.receiptFooter || 'Simpan struk ini sebagai bukti pembayaran')}
</div>`;
  }

  html += `
</body>
</html>`;

  return html;
}

interface ReceiptPrinterProps {
  receiptData: ReceiptData | null;
  onPrint?: (type: ReceiptType) => void;
}

export function useReceiptPrinter() {
  const [storeInfo, setStoreInfo] = useState<StoreInfo>(DEFAULT_STORE);

  useEffect(() => {
    const loadSettings = () => {
      const apply = (settings: any) => {
        setStoreInfo({
          name: settings.store_name || DEFAULT_STORE.name,
          address: settings.store_address || DEFAULT_STORE.address,
          phone: settings.store_phone || DEFAULT_STORE.phone,
          receiptHeader: settings.receipt_header || DEFAULT_STORE.receiptHeader,
          receiptFooter: settings.receipt_footer || DEFAULT_STORE.receiptFooter,
        });
      };

      // Try localStorage first
      const cached = localStorage.getItem('store_settings');
      if (cached) {
        try {
          apply(JSON.parse(cached));
          return;
        } catch {}
      }

      settingsApi.getAll().then((settings) => {
        apply(settings);
        localStorage.setItem('store_settings', JSON.stringify(settings));
      }).catch(() => {
        // Use defaults if settings fetch fails
      });
    };

    loadSettings();
  }, []);

  const printReceipt = useCallback((data: ReceiptData, type: ReceiptType) => {
    const html = buildReceiptHTML(data, type, storeInfo);
    if (!html) {
      alert('Tidak ada item untuk dicetak.');
      return;
    }

    const printWindow = window.open('', '_blank', 'width=350,height=600');
    if (!printWindow) {
      alert('Popup diblokir. Izinkan popup untuk mencetak struk.');
      return;
    }

    printWindow.document.write(html);
    printWindow.document.close();

    // Wait for content to render, then print
    let printed = false;
    const doPrint = () => {
      if (printed) return;
      printed = true;
      try {
        printWindow.focus();
        printWindow.print();
        setTimeout(() => printWindow.close(), 500);
      } catch {
        // Window may already be closed
      }
    };

    printWindow.onload = doPrint;

    // Fallback if onload doesn't fire (some browsers)
    setTimeout(doPrint, 1000);
  }, [storeInfo]);

  return { printReceipt };
}

export default function ReceiptPrintButtons({
  receiptData,
  onPrintStart,
}: {
  receiptData: ReceiptData | null;
  onPrintStart?: () => void;
}) {
  const { printReceipt } = useReceiptPrinter();

  if (!receiptData) return null;

  const handlePrint = (type: ReceiptType) => {
    onPrintStart?.();
    printReceipt(receiptData, type);
  };

  return (
    <div className="flex flex-col gap-1.5 w-full">
      <button
        onClick={() => handlePrint('customer')}
        className="flex-1 flex items-center justify-center gap-2 rounded-xl border border-brand-200 py-2.5 text-xs font-semibold text-brand-600 hover:bg-brand-50 active:scale-[0.98] transition-all cursor-pointer"
      >
        Cetak Struk
      </button>
    </div>
  );
}
