import React from 'react';
import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';
import { Transaction } from '../types';
import { X, Send, Download, Printer, CheckCircle2, Store, Calendar, User, Phone, ShoppingBag } from 'lucide-react';

interface Props {
  transaction: Transaction | null;
  isOpen: boolean;
  onClose: () => void;
}

export const ReceiptModal: React.FC<Props> = ({ transaction, isOpen, onClose }) => {
  if (!isOpen || !transaction) return null;

  const dateFormatted = new Date(transaction.date).toLocaleDateString('id-ID', {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  });

  // Generate WhatsApp Message Link (wa.me)
  const generateWhatsAppUrl = () => {
    let itemsText = transaction.items.map((item, idx) => {
      const priceTag = item.priceType && item.priceType !== 'Eceran' ? ` (${item.priceType}${item.priceNote ? `: ${item.priceNote}` : ''})` : '';
      return `${idx + 1}. *${item.productName} - ${item.variantName}*${priceTag}\n   ${item.quantity} x Rp ${item.sellPrice.toLocaleString('id-ID')} = Rp ${item.subtotal.toLocaleString('id-ID')}`;
    }).join('\n');

    const message = `*TOKO MAKMUR - STRUK BELANJA*
----------------------------------------
No. Transaksi: ${transaction.transactionCode}
Tanggal: ${dateFormatted}
Nama Pelanggan: ${transaction.customerName || 'Pelanggan Toko'}
Pembayaran: ${transaction.paymentMethod}

*Rincian Pembelian:*
${itemsText}
----------------------------------------
Subtotal: Rp ${transaction.totalAmount.toLocaleString('id-ID')}
${transaction.discount > 0 ? `Diskon: -Rp ${transaction.discount.toLocaleString('id-ID')}\n` : ''}*TOTAL BAYAR: Rp ${transaction.finalAmount.toLocaleString('id-ID')}*

Terima kasih telah berbelanja di *Toko Makmur*! Semoga rezeki Anda melimpah & berkah.`;

    const encodedMessage = encodeURIComponent(message);
    let rawPhone = transaction.customerPhone ? transaction.customerPhone.replace(/[^0-9]/g, '') : '';
    if (!rawPhone) {
      rawPhone = '085224503737';
    }
    if (rawPhone.startsWith('0')) {
      rawPhone = '62' + rawPhone.slice(1);
    }

    if (rawPhone) {
      return `https://wa.me/${rawPhone}?text=${encodedMessage}`;
    }
    return `https://wa.me/?text=${encodedMessage}`;
  };

  // Generate & Download PDF Receipt
  const handleDownloadPdf = () => {
    const doc = new jsPDF({
      orientation: 'portrait',
      unit: 'mm',
      format: [80, 160] // Receipt thermal 80mm format
    });

    // Store Header
    doc.setFont('helvetica', 'bold');
    doc.setFontSize(13);
    doc.text('TOKO MAKMUR', 40, 10, { align: 'center' });

    doc.setFont('helvetica', 'normal');
    doc.setFontSize(8);
    doc.text('Sistem Monitoring & Kasir Sembako', 40, 14, { align: 'center' });
    doc.text('Jl. Raya Sembako Makmur No. 1', 40, 18, { align: 'center' });

    // Clean divider line
    doc.setLineWidth(0.2);
    doc.setLineDashPattern([1, 1], 0);
    doc.line(4, 21, 76, 21);

    // Transaction Details
    doc.setFontSize(8);
    doc.text(`No. TRX : ${transaction.transactionCode}`, 4, 26);
    doc.text(`Tgl     : ${dateFormatted}`, 4, 30);
    doc.text(`Pembeli : ${transaction.customerName || 'Pelanggan Toko'}`, 4, 34);
    doc.text(`Bayar   : ${transaction.paymentMethod}`, 4, 38);

    doc.line(4, 41, 76, 41);

    // Items Table
    const tableData = transaction.items.map(item => [
      `${item.productName}\n(${item.variantName})`,
      `${item.quantity}`,
      `Rp ${item.sellPrice.toLocaleString('id-ID')}`,
      `Rp ${item.subtotal.toLocaleString('id-ID')}`
    ]);

    autoTable(doc, {
      startY: 43,
      margin: { left: 4, right: 4 },
      head: [['Barang', 'Qty', 'Harga', 'Subtotal']],
      body: tableData,
      theme: 'plain',
      styles: { fontSize: 7, cellPadding: 1 },
      headStyles: { fontStyle: 'bold' },
      columnStyles: {
        0: { cellWidth: 28 },
        1: { cellWidth: 10, halign: 'center' },
        2: { cellWidth: 16, halign: 'right' },
        3: { cellWidth: 18, halign: 'right' }
      }
    });

    const finalY = (doc as any).lastAutoTable?.finalY || 80;

    doc.setLineDashPattern([1, 1], 0);
    doc.line(4, finalY + 2, 76, finalY + 2);

    let curY = finalY + 7;
    if (transaction.discount > 0) {
      doc.setFont('helvetica', 'normal');
      doc.setFontSize(8);
      doc.text(`Subtotal: Rp ${transaction.totalAmount.toLocaleString('id-ID')}`, 76, curY, { align: 'right' });
      curY += 4;
      doc.text(`Diskon: -Rp ${transaction.discount.toLocaleString('id-ID')}`, 76, curY, { align: 'right' });
      curY += 4;
    }

    doc.setFont('helvetica', 'bold');
    doc.setFontSize(9);
    doc.text(`TOTAL: Rp ${transaction.finalAmount.toLocaleString('id-ID')}`, 76, curY, { align: 'right' });

    doc.setFont('helvetica', 'normal');
    doc.setFontSize(7);
    doc.text('Terima kasih atas kunjungan Anda!', 40, curY + 8, { align: 'center' });
    doc.text('Semoga rezeki Anda melimpah & berkah', 40, curY + 12, { align: 'center' });

    doc.save(`Struk_${transaction.transactionCode}.pdf`);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 backdrop-blur-sm p-2 sm:p-4 overflow-y-auto">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md border border-slate-100 my-auto max-h-[95vh] flex flex-col overflow-hidden">
        
        {/* Header */}
        <div className="bg-gradient-to-r from-emerald-600 to-teal-700 text-white px-4 sm:px-6 py-3.5 flex items-center justify-between shrink-0">
          <div className="flex items-center gap-2.5">
            <CheckCircle2 className="w-5 h-5 sm:w-6 sm:h-6 text-emerald-200 shrink-0" />
            <div>
              <h3 className="font-bold text-sm sm:text-base leading-tight">Transaksi Berhasil</h3>
              <p className="text-emerald-100 text-[11px] sm:text-xs">Struk & Bukti Pembayaran Toko Makmur</p>
            </div>
          </div>
          <button onClick={onClose} className="p-1 rounded-lg hover:bg-white/20 text-white transition">
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Receipt Content Body */}
        <div className="p-4 sm:p-6 space-y-4 overflow-y-auto flex-1">
          
          <div className="bg-slate-50 border border-slate-200 rounded-2xl p-4 font-mono text-xs space-y-3">
            
            {/* Store Banner */}
            <div className="text-center pb-2 border-b border-dashed border-slate-300 space-y-1">
              <h4 className="font-black text-slate-900 text-sm tracking-wider uppercase">TOKO MAKMUR</h4>
              <p className="text-[10px] text-slate-500">Sistem Monitoring & Kasir Sembako</p>
            </div>

            {/* Transaction Meta */}
            <div className="space-y-1 text-slate-700 text-[11px]">
              <div className="flex justify-between">
                <span className="text-slate-400">Kode TRX:</span>
                <span className="font-bold">{transaction.transactionCode}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-slate-400">Waktu:</span>
                <span>{dateFormatted}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-slate-400">Pembeli:</span>
                <span className="font-semibold">{transaction.customerName || 'Pelanggan Umum'}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-slate-400">Pembayaran:</span>
                <span className="px-1.5 py-0.2 bg-emerald-100 text-emerald-800 rounded font-bold text-[10px]">
                  {transaction.paymentMethod}
                </span>
              </div>
            </div>

            {/* Items List */}
            <div className="pt-2 border-t border-dashed border-slate-300 space-y-2">
              <span className="text-[10px] font-bold text-slate-400 uppercase">Daftar Belanja:</span>
              {transaction.items.map((item, idx) => (
                <div key={idx} className="flex justify-between text-[11px] text-slate-800">
                  <div>
                    <span className="font-bold">{item.productName}</span>
                    <span className="text-slate-500 block text-[10px]">
                      {item.variantName}
                      {item.priceType && item.priceType !== 'Eceran' && (
                        <span className="ml-1 text-indigo-700 font-bold">({item.priceType})</span>
                      )}
                    </span>
                  </div>
                  <div className="text-right">
                    <span>{item.quantity} x {item.sellPrice.toLocaleString('id-ID')}</span>
                    <span className="font-bold block text-slate-900">
                      Rp {item.subtotal.toLocaleString('id-ID')}
                    </span>
                  </div>
                </div>
              ))}
            </div>

            {/* Totals */}
            <div className="pt-2 border-t border-dashed border-slate-300 space-y-1 text-right">
              {transaction.discount > 0 && (
                <div className="flex justify-between text-slate-500 text-[11px]">
                  <span>Diskon:</span>
                  <span className="text-rose-600">-Rp {transaction.discount.toLocaleString('id-ID')}</span>
                </div>
              )}
              <div className="flex justify-between text-sm font-black text-emerald-700 pt-1">
                <span>Total Bayar:</span>
                <span>Rp {transaction.finalAmount.toLocaleString('id-ID')}</span>
              </div>
            </div>

          </div>

          {/* Quick Action Options */}
          <div className="space-y-2 pt-1">
            <a
              href={generateWhatsAppUrl()}
              target="_blank"
              rel="noopener noreferrer"
              className="w-full py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs rounded-xl flex items-center justify-center gap-2 shadow-sm transition"
            >
              <Send className="w-4 h-4" /> Kirim Struk via WhatsApp ({transaction.customerPhone || '085224503737'})
            </a>

            <button
              onClick={handleDownloadPdf}
              className="w-full py-2.5 bg-slate-800 hover:bg-slate-900 text-white font-bold text-xs rounded-xl flex items-center justify-center gap-2 transition"
            >
              <Download className="w-4 h-4" /> Cetak ke File PDF
            </button>
          </div>

        </div>

        <div className="px-6 py-3 bg-slate-50 border-t border-slate-100 text-right">
          <button
            onClick={onClose}
            className="px-4 py-2 bg-slate-200 hover:bg-slate-300 text-slate-800 text-xs font-semibold rounded-xl transition"
          >
            Tutup Struk
          </button>
        </div>

      </div>
    </div>
  );
};
