import { forwardRef } from 'react';
import { formatCurrency, formatDateTime, paymentLabel } from '../utils/formatters';

const Receipt = forwardRef(({ sale, settings }, ref) => {
  if (!sale) return null;
  const name    = settings?.business_name    || 'Antang Garage Oli';
  const address = settings?.business_address || '';
  const phone   = settings?.business_phone   || '';
  const message = settings?.receipt_message  || 'Terima kasih telah berkunjung!';
  return (
    <div ref={ref} id="receipt-print" className="p-4 bg-white font-mono text-xs" style={{ width: '80mm' }}>
      <div className="text-center mb-3">
        <p className="text-base font-bold">🔧 {name.toUpperCase()}</p>
        {address && <p className="text-gray-600">{address}</p>}
        {phone   && <p className="text-gray-600">Telp / WA : {phone}</p>}
        <p className="text-gray-400 border-t border-dashed mt-1 pt-1">{formatDateTime(sale.created_at)}</p>
      </div>

      <div className="border-t border-dashed py-1 mb-2 text-xs">
        <div className="flex justify-between"><span>No. Invoice</span><span className="font-bold">{sale.invoice_no}</span></div>
        <div className="flex justify-between"><span>Kasir</span><span>{sale.cashier_name}</span></div>
        <div className="flex justify-between"><span>Pembayaran</span><span>{paymentLabel(sale.payment_method)}</span></div>
      </div>

      <div className="border-t border-dashed py-2 mb-2">
        {(sale.items || []).map((item, i) => (
          <div key={i} className="mb-1.5">
            <div className="font-medium">{item.item_name}</div>
            <div className="flex justify-between text-gray-600 ml-2">
              <span>{item.qty} x {formatCurrency(item.unit_price)}</span>
              <span>{formatCurrency(item.subtotal)}</span>
            </div>
          </div>
        ))}
      </div>

      <div className="border-t border-dashed py-2">
        <div className="flex justify-between font-bold text-sm">
          <span>TOTAL</span>
          <span>{formatCurrency(sale.total_amount)}</span>
        </div>
        {sale.payment_method === 'tunai' && (
          <>
            <div className="flex justify-between mt-1"><span>Bayar</span><span>{formatCurrency(sale.amount_paid)}</span></div>
            <div className="flex justify-between font-bold text-green-700"><span>Kembali</span><span>{formatCurrency(sale.change_amount)}</span></div>
          </>
        )}
      </div>

      <div className="text-center mt-3 border-t border-dashed pt-2 text-gray-500">
        <p>{message}</p>
      </div>
    </div>
  );
});

Receipt.displayName = 'Receipt';
export default Receipt;
