import React, { useState, useEffect, useRef, useMemo } from 'react';
import confetti from 'canvas-confetti';
import Swal from 'sweetalert2';
import { useStore } from '../context/StoreContext';
import { CartItem, Transaction } from '../types';
import { ReceiptModal } from '../components/ReceiptModal';
import { SearchableSelect } from '../components/SearchableSelect';
import { calculateVariantPriceForQty, formatTierRulesSummary } from '../utils/tierPricing';
import { ShoppingCart, Plus, Minus, Trash2, Barcode, CheckCircle2, User, Phone, DollarSign, Send, FileText, AlertCircle, Sparkles, X } from 'lucide-react';

export const PosPage: React.FC = () => {
  const { db, addTransaction, findVariantByBarcode } = useStore();

  const [cart, setCart] = useState<CartItem[]>([]);
  const [customerName, setCustomerName] = useState('');
  const [customerPhone, setCustomerPhone] = useState('085224503737');
  const [paymentMethod, setPaymentMethod] = useState<'Tunai' | 'QRIS' | 'Transfer Bank'>('Tunai');
  const [discount, setDiscount] = useState<number>(0);
  const [notes, setNotes] = useState('');

  const [barcodeInput, setBarcodeInput] = useState('');
  const [isPosSuggestOpen, setIsPosSuggestOpen] = useState(false);
  const posSearchRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (posSearchRef.current && !posSearchRef.current.contains(event.target as Node)) {
        setIsPosSuggestOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const posSuggestions = useMemo(() => {
    const query = barcodeInput.trim().toLowerCase();
    if (!query) return [];

    const list: Array<{
      productId: string;
      productName: string;
      variantId: string;
      variantName: string;
      barcode: string;
      category: string;
      sellPrice: number;
      stock: number;
      unit: string;
    }> = [];

    for (const p of db.products) {
      for (const v of p.variants) {
        if (
          p.name.toLowerCase().includes(query) ||
          v.variantName.toLowerCase().includes(query) ||
          v.barcode.toLowerCase().includes(query) ||
          p.category.toLowerCase().includes(query)
        ) {
          list.push({
            productId: p.id,
            productName: p.name,
            variantId: v.id,
            variantName: v.variantName,
            barcode: v.barcode,
            category: p.category,
            sellPrice: v.sellPrice,
            stock: v.stock,
            unit: v.unit
          });
        }
      }
    }
    return list.slice(0, 6);
  }, [db.products, barcodeInput]);
  const [selectedVariantSelect, setSelectedVariantSelect] = useState('');
  const [scanSuccessMessage, setScanSuccessMessage] = useState<string | null>(null);
  const [completedTransaction, setCompletedTransaction] = useState<Transaction | null>(null);
  const [isReceiptOpen, setIsReceiptOpen] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);

  // Play Beep Sound
  const playBeep = () => {
    try {
      const audioCtx = new (window.AudioContext || (window as any).webkitAudioContext)();
      const osc = audioCtx.createOscillator();
      const gain = audioCtx.createGain();
      osc.type = 'sine';
      osc.frequency.setValueAtTime(880, audioCtx.currentTime);
      gain.gain.setValueAtTime(0.1, audioCtx.currentTime);
      osc.connect(gain);
      gain.connect(audioCtx.destination);
      osc.start();
      osc.stop(audioCtx.currentTime + 0.15);
    } catch (e) {}
  };

  // Add Item to Cart Helper
  const addItemToCart = (variantId: string, productId: string) => {
    setErrorMsg(null);
    const product = db.products.find(p => p.id === productId);
    if (!product) return;
    const variant = product.variants.find(v => v.id === variantId);
    if (!variant) return;

    if (variant.stock <= 0) {
      setErrorMsg(`Stok barang "${product.name} - ${variant.variantName}" sedang habis!`);
      return;
    }

    setCart(prev => {
      const existingIdx = prev.findIndex(item => item.variantId === variantId);
      if (existingIdx >= 0) {
        const existing = prev[existingIdx];
        if (existing.quantity >= variant.stock) {
          setErrorMsg(`Jumlah melebihi stok yang tersedia (${variant.stock} ${variant.unit})!`);
          return prev;
        }
        playBeep();
        return prev.map((item, idx) => {
          if (idx === existingIdx) {
            const newQty = item.quantity + 1;
            const priceCalc = item.priceType === 'Eceran' 
              ? calculateVariantPriceForQty(variant, newQty)
              : { unitPrice: item.sellPrice, subtotal: newQty * item.sellPrice, tierNote: item.appliedTierNote, savedAmount: 0 };
            return {
              ...item,
              quantity: newQty,
              sellPrice: priceCalc.unitPrice,
              subtotal: priceCalc.subtotal,
              appliedTierNote: priceCalc.tierNote,
              savedAmount: priceCalc.savedAmount
            };
          }
          return item;
        });
      }

      playBeep();
      const initialCalc = calculateVariantPriceForQty(variant, 1);
      return [
        ...prev,
        {
          productId: product.id,
          productName: product.name,
          variantId: variant.id,
          variantName: variant.variantName,
          unit: variant.unit,
          barcode: variant.barcode,
          quantity: 1,
          buyPrice: variant.buyPrice,
          sellPrice: initialCalc.unitPrice,
          originalSellPrice: variant.sellPrice,
          wholesalePrice: variant.wholesalePrice || Math.round(variant.sellPrice * 0.95),
          priceType: 'Eceran',
          priceNote: '',
          appliedTierNote: initialCalc.tierNote,
          savedAmount: initialCalc.savedAmount,
          maxStock: variant.stock,
          subtotal: initialCalc.subtotal
        }
      ];
    });
  };

  // Update Custom Price / Wholesale Price per item in Cart
  const updateItemPrice = (
    variantId: string,
    priceType: 'Eceran' | 'Grosir' | 'Khusus',
    customPrice?: number,
    priceNote?: string
  ) => {
    setCart(prev => prev.map(item => {
      if (item.variantId === variantId) {
        const product = db.products.find(p => p.id === item.productId);
        const variant = product?.variants.find(v => v.id === item.variantId);

        let newSellPrice = item.originalSellPrice || item.sellPrice;
        let appliedNote = undefined;
        let saved = 0;

        if (priceType === 'Grosir') {
          newSellPrice = item.wholesalePrice || Math.round(item.originalSellPrice * 0.95);
          appliedNote = 'Harga Grosir / Reseller';
          saved = Math.max(0, (item.quantity * item.originalSellPrice) - (item.quantity * newSellPrice));
        } else if (priceType === 'Khusus' && customPrice !== undefined) {
          newSellPrice = customPrice;
          appliedNote = 'Harga Khusus Penyesuaian';
        } else if (variant) {
          const calc = calculateVariantPriceForQty(variant, item.quantity);
          newSellPrice = calc.unitPrice;
          appliedNote = calc.tierNote;
          saved = calc.savedAmount;
        }

        const note = priceNote !== undefined 
          ? priceNote 
          : (priceType === 'Grosir' ? 'Dijual lagi / Reseller' : priceType === 'Khusus' ? 'Harga khusus / kenal' : '');

        return {
          ...item,
          sellPrice: newSellPrice,
          priceType,
          priceNote: note,
          appliedTierNote: appliedNote,
          savedAmount: saved,
          subtotal: item.quantity * newSellPrice
        };
      }
      return item;
    }));
  };

  // Add via Barcode Input Search
  const handleAddByBarcode = (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMsg(null);
    if (!barcodeInput.trim()) return;

    const found = findVariantByBarcode(barcodeInput.trim());
    if (found) {
      addItemToCart(found.variant.id, found.product.id);
      setBarcodeInput('');
    } else {
      const msg = `Barcode "${barcodeInput}" tidak ditemukan dalam database!`;
      setErrorMsg(msg);
      Swal.fire({
        icon: 'error',
        title: 'Barcode Tidak Ditemukan',
        text: msg,
        confirmButtonColor: '#059669'
      });
    }
  };

  // Add via Dropdown Select
  const handleSelectDropdownItem = (val: string) => {
    if (!val) return;
    const [prodId, varId] = val.split('|');
    addItemToCart(varId, prodId);
    setSelectedVariantSelect('');
  };

  // Quantity Change
  const updateQuantity = (variantId: string, delta: number) => {
    setCart(prev => prev.map(item => {
      if (item.variantId === variantId) {
        const newQty = item.quantity + delta;
        if (newQty <= 0) return null as any;
        if (newQty > item.maxStock) {
          setErrorMsg(`Stok tidak mencukupi! Maksimal ${item.maxStock} ${item.unit}`);
          return item;
        }

        const product = db.products.find(p => p.id === item.productId);
        const variant = product?.variants.find(v => v.id === item.variantId);

        if (item.priceType === 'Eceran' && variant) {
          const calc = calculateVariantPriceForQty(variant, newQty);
          return {
            ...item,
            quantity: newQty,
            sellPrice: calc.unitPrice,
            subtotal: calc.subtotal,
            appliedTierNote: calc.tierNote,
            savedAmount: calc.savedAmount
          };
        }

        return {
          ...item,
          quantity: newQty,
          subtotal: newQty * item.sellPrice
        };
      }
      return item;
    }).filter(Boolean));
  };

  const removeItem = (variantId: string) => {
    setCart(prev => prev.filter(item => item.variantId !== variantId));
  };

  // Calculations
  const rawTotal = cart.reduce((acc, item) => acc + item.subtotal, 0);
  const totalCost = cart.reduce((acc, item) => acc + (item.quantity * item.buyPrice), 0);
  const finalTotal = Math.max(0, rawTotal - discount);
  const profit = Math.max(0, finalTotal - totalCost);

  // Submit Transaction
  const handleSaveTransaction = () => {
    setErrorMsg(null);

    if (cart.length === 0) {
      const msg = 'Keranjang belanja masih kosong! Tambahkan barang terlebih dahulu.';
      setErrorMsg(msg);
      Swal.fire({
        icon: 'warning',
        title: 'Keranjang Kosong',
        text: msg,
        confirmButtonColor: '#059669'
      });
      return;
    }

    const trx = addTransaction({
      customerName: customerName.trim() || 'Pelanggan Umum',
      customerPhone: customerPhone.trim(),
      items: cart,
      paymentMethod,
      totalAmount: rawTotal,
      totalProfit: profit,
      discount,
      finalAmount: finalTotal,
      notes
    });

    // Fire Confetti
    confetti({
      particleCount: 80,
      spread: 70,
      origin: { y: 0.6 }
    });

    Swal.fire({
      icon: 'success',
      title: 'Transaksi Berhasil!',
      text: `Total Pembayaran: Rp ${finalTotal.toLocaleString('id-ID')} (${paymentMethod})`,
      timer: 2000,
      showConfirmButton: false
    });

    setCompletedTransaction(trx);
    setIsReceiptOpen(true);

    // Reset Cart
    setCart([]);
    setCustomerName('');
    setCustomerPhone('085224503737');
    setDiscount(0);
    setNotes('');
  };

  return (
    <div className="space-y-6">
      
      {/* Header Bar */}
      <div className="bg-gradient-to-r from-emerald-600 to-teal-700 text-white rounded-2xl p-6 shadow-md flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-2">
            <ShoppingCart className="w-6 h-6 text-emerald-200" />
            <h2 className="text-xl font-bold">Kasir & Checkout Transaksi</h2>
          </div>
          <p className="text-xs text-emerald-100 mt-1">
            Cari barcode / pilih varian barang untuk dimasukkan ke tabel belanja. Struk siap dikirim via WhatsApp (WA.me) & PDF!
          </p>
        </div>
      </div>

      {errorMsg && (
        <div className="p-4 bg-rose-50 border border-rose-200 rounded-2xl flex items-center justify-between text-rose-800 text-xs font-semibold">
          <div className="flex items-center gap-2">
            <AlertCircle className="w-5 h-5 text-rose-600 shrink-0" />
            <span>{errorMsg}</span>
          </div>
          <button onClick={() => setErrorMsg(null)} className="text-rose-500 hover:text-rose-700">Tutup</button>
        </div>
      )}

      {/* POS WORKSPACE GRID */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        
        {/* Left Column: Input Barcode & Shopping Table */}
        <div className="lg:col-span-2 space-y-4">

          {scanSuccessMessage && (
            <div className="p-3 bg-emerald-600 text-white font-bold text-xs rounded-2xl shadow-md flex items-center gap-2 animate-in fade-in zoom-in-95 duration-150">
              <CheckCircle2 className="w-5 h-5 text-emerald-200 shrink-0" />
              <span>{scanSuccessMessage}</span>
            </div>
          )}

          {/* Item Add Control */}
          <div className="bg-white border border-slate-200 rounded-2xl p-4 shadow-2xs space-y-3">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              
              {/* Type Barcode or Name */}
              <form onSubmit={(e) => { e.preventDefault(); setIsPosSuggestOpen(false); handleAddByBarcode(e); }} className="flex gap-2">
                <div ref={posSearchRef} className="relative flex-1">
                  <Barcode className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
                  <input
                    type="text"
                    value={barcodeInput}
                    onFocus={() => setIsPosSuggestOpen(true)}
                    onChange={(e) => {
                      setBarcodeInput(e.target.value);
                      setIsPosSuggestOpen(true);
                    }}
                    placeholder="Ketik nama barang / barcode..."
                    className="w-full pl-9 pr-7 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs font-mono font-semibold focus:ring-2 focus:ring-emerald-500 focus:bg-white transition"
                  />
                  {barcodeInput && (
                    <button
                      type="button"
                      onClick={() => {
                        setBarcodeInput('');
                        setIsPosSuggestOpen(false);
                      }}
                      className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-0.5"
                    >
                      <X className="w-3.5 h-3.5" />
                    </button>
                  )}

                  {/* POS Auto-Suggest Dropdown */}
                  {isPosSuggestOpen && barcodeInput.trim().length > 0 && (
                    <div className="absolute top-full left-0 right-0 mt-1.5 bg-white rounded-2xl shadow-2xl border border-slate-200 z-50 overflow-hidden text-xs py-1 animate-in fade-in zoom-in-95 duration-100">
                      <div className="px-3.5 py-2 bg-slate-50 border-b border-slate-100 text-[10px] font-bold text-slate-500 uppercase tracking-wider flex justify-between items-center">
                        <span>Rekomendasi Barang Kasir ({posSuggestions.length})</span>
                        <span className="text-[10px] font-normal text-slate-400">Klik untuk Masukkan Kasir</span>
                      </div>

                      {posSuggestions.length === 0 ? (
                        <div className="p-4 text-center text-slate-400 italic text-xs">
                          Tidak ditemukan barang yang cocok
                        </div>
                      ) : (
                        <div className="max-h-60 overflow-y-auto divide-y divide-slate-100">
                          {posSuggestions.map((item) => (
                            <button
                              key={`${item.productId}-${item.variantId}`}
                              type="button"
                              onClick={() => {
                                addItemToCart(item.variantId, item.productId);
                                setBarcodeInput('');
                                setIsPosSuggestOpen(false);
                              }}
                              className="w-full text-left px-3.5 py-2.5 hover:bg-emerald-50 transition flex items-center justify-between gap-2 group"
                            >
                              <div className="min-w-0 flex-1">
                                <div className="font-bold text-slate-800 group-hover:text-emerald-800 text-xs truncate">
                                  {item.productName} - {item.variantName}
                                </div>
                                <div className="flex items-center gap-2 mt-0.5 text-[10px] text-slate-400">
                                  <span className="font-mono text-slate-500 font-semibold">
                                    {item.barcode ? `Barcode: ${item.barcode}` : 'Tanpa Barcode'}
                                  </span>
                                  <span>•</span>
                                  <span>{item.category}</span>
                                </div>
                              </div>
                              <div className="text-right shrink-0">
                                <div className="font-extrabold text-emerald-700 text-xs">
                                  Rp {item.sellPrice.toLocaleString('id-ID')}
                                </div>
                                <div className="text-[10px] text-slate-400">
                                  Stok: <span className={item.stock > 0 ? "font-bold text-slate-700" : "font-bold text-rose-600"}>{item.stock} {item.unit}</span>
                                </div>
                              </div>
                            </button>
                          ))}
                        </div>
                      )}
                    </div>
                  )}
                </div>
                <button
                  type="submit"
                  className="px-3.5 py-2 bg-emerald-600 text-white font-bold text-xs rounded-xl hover:bg-emerald-700 transition shrink-0"
                >
                  Tambah
                </button>
              </form>

              {/* Select From Dropdown */}
              <SearchableSelect
                options={db.products.flatMap(p =>
                  p.variants.map(v => ({
                    value: `${p.id}|${v.id}`,
                    label: `${p.name} - ${v.variantName}`,
                    sublabel: `Rp ${v.sellPrice.toLocaleString('id-ID')} | Stok: ${v.stock} ${v.unit}`,
                    badge: p.category
                  }))
                )}
                value={selectedVariantSelect}
                onChange={(val) => {
                  setSelectedVariantSelect(val);
                  handleSelectDropdownItem(val);
                  setTimeout(() => setSelectedVariantSelect(''), 100);
                }}
                placeholder="-- Cari & Pilih Barang dari Katalog --"
                searchPlaceholder="Ketik nama barang, varian, atau kategori..."
              />

            </div>
          </div>

          {/* SHOPPING TABLE */}
          <div className="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-2xs">
            <div className="p-4 bg-slate-50 border-b border-slate-200 flex items-center justify-between">
              <h3 className="font-bold text-slate-900 text-sm flex items-center gap-2">
                <ShoppingCart className="w-4 h-4 text-emerald-600" />
                Tabel Daftar Belanja Pembeli ({cart.length} Jenis Barang)
              </h3>
              {cart.length > 0 && (
                <button
                  onClick={() => setCart([])}
                  className="text-xs text-rose-600 font-semibold hover:underline"
                >
                  Kosongkan Keranjang
                </button>
              )}
            </div>

            {cart.length === 0 ? (
              <div className="p-12 text-center space-y-2">
                <ShoppingCart className="w-12 h-12 text-slate-300 mx-auto" />
                <p className="text-xs font-bold text-slate-600">Keranjang Belanja Masih Kosong</p>
                <p className="text-xs text-slate-400">Arahkan kamera ke barcode barang atau pilih barang dari menu di atas.</p>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs">
                  <thead className="bg-slate-50/50 text-slate-500 font-bold border-b border-slate-100">
                    <tr>
                      <th className="p-3 pl-4">Nama Barang & Varian</th>
                      <th className="p-3">Harga</th>
                      <th className="p-3 text-center">Jumlah (Qty)</th>
                      <th className="p-3">Subtotal</th>
                      <th className="p-3 pr-4 text-right">Aksi</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {cart.map((item) => (
                      <tr key={item.variantId} className="hover:bg-slate-50/80 transition align-top">
                        <td className="p-3 pl-4">
                          <div className="font-bold text-slate-900">{item.productName}</div>
                          <div className="text-[11px] text-emerald-700 font-semibold">
                            Varian: {item.variantName}
                          </div>
                          <div className="text-[10px] text-slate-400 font-mono">Barcode: {item.barcode}</div>

                          {/* Price Tag Badge */}
                          {item.appliedTierNote && (
                            <span className="inline-block mt-1 px-1.5 py-0.5 bg-emerald-100 text-emerald-900 rounded font-bold text-[10px] border border-emerald-200">
                              ✨ {item.appliedTierNote}
                            </span>
                          )}
                          {item.priceType === 'Grosir' && (
                            <span className="inline-block mt-1 px-1.5 py-0.5 bg-indigo-100 text-indigo-800 rounded font-bold text-[10px]">
                              🏷️ Grosir / Reseller ({item.priceNote || 'Dijual lagi'})
                            </span>
                          )}
                          {item.priceType === 'Khusus' && (
                            <span className="inline-block mt-1 px-1.5 py-0.5 bg-amber-100 text-amber-800 rounded font-bold text-[10px]">
                              🏷️ Harga Khusus ({item.priceNote || 'Penyesuaian'})
                            </span>
                          )}
                        </td>

                        <td className="p-3">
                          <div className="space-y-1.5">
                            {/* Current Unit Price Display */}
                            <div>
                              <div className="font-bold text-slate-900 text-xs flex items-center gap-1">
                                <span>Rp {item.sellPrice.toLocaleString('id-ID')}</span>
                                {item.originalSellPrice && item.sellPrice < item.originalSellPrice && (
                                  <span className="line-through text-slate-400 text-[10px] font-normal">
                                    Rp {item.originalSellPrice.toLocaleString('id-ID')}
                                  </span>
                                )}
                              </div>
                              {item.savedAmount && item.savedAmount > 0 ? (
                                <div className="text-[10px] font-bold text-emerald-700 mt-0.5">
                                  Hemat Rp {item.savedAmount.toLocaleString('id-ID')}
                                </div>
                              ) : null}
                            </div>

                            {/* Price Tier Toggles */}
                            <div className="flex flex-wrap gap-1">
                              <button
                                type="button"
                                onClick={() => updateItemPrice(item.variantId, 'Eceran')}
                                className={`px-1.5 py-0.5 rounded text-[10px] font-bold transition ${
                                  item.priceType === 'Eceran' || !item.priceType
                                    ? 'bg-slate-800 text-white'
                                    : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
                                }`}
                              >
                                Eceran
                              </button>

                              <button
                                type="button"
                                onClick={() => updateItemPrice(item.variantId, 'Grosir')}
                                className={`px-1.5 py-0.5 rounded text-[10px] font-bold transition ${
                                  item.priceType === 'Grosir'
                                    ? 'bg-indigo-600 text-white'
                                    : 'bg-indigo-50 text-indigo-700 hover:bg-indigo-100'
                                }`}
                                title="Harga khusus untuk dijual kembali"
                              >
                                Grosir
                              </button>

                              <button
                                type="button"
                                onClick={() => updateItemPrice(item.variantId, 'Khusus', item.sellPrice)}
                                className={`px-1.5 py-0.5 rounded text-[10px] font-bold transition ${
                                  item.priceType === 'Khusus'
                                    ? 'bg-amber-600 text-white'
                                    : 'bg-amber-50 text-amber-700 hover:bg-amber-100'
                                }`}
                                title="Harga khusus kenal / penyesuaian manual"
                              >
                                Khusus
                              </button>
                            </div>

                            {/* Custom Price Inputs when 'Khusus' is selected */}
                            {item.priceType === 'Khusus' && (
                              <div className="pt-1 space-y-1">
                                <div className="flex items-center gap-1">
                                  <span className="text-[10px] text-slate-500 font-bold">Rp</span>
                                  <input
                                    type="number"
                                    value={item.sellPrice}
                                    onChange={(e) => updateItemPrice(item.variantId, 'Khusus', Number(e.target.value), item.priceNote)}
                                    className="w-20 px-1.5 py-0.5 bg-amber-50 border border-amber-300 rounded text-xs font-bold text-slate-900 focus:ring-1 focus:ring-amber-500"
                                  />
                                </div>
                                <input
                                  type="text"
                                  value={item.priceNote || ''}
                                  onChange={(e) => updateItemPrice(item.variantId, 'Khusus', item.sellPrice, e.target.value)}
                                  placeholder="Alasan / Catatan (cth: Kenal / Dijual lagi)..."
                                  className="w-28 px-1.5 py-0.5 bg-slate-50 border border-slate-200 rounded text-[10px] focus:ring-1 focus:ring-amber-500"
                                />
                              </div>
                            )}
                          </div>
                        </td>

                        <td className="p-3 text-center">
                          <div className="inline-flex items-center border border-slate-200 rounded-lg overflow-hidden bg-white">
                            <button
                              onClick={() => updateQuantity(item.variantId, -1)}
                              className="p-1 hover:bg-slate-100 text-slate-600 transition"
                            >
                              <Minus className="w-3.5 h-3.5" />
                            </button>
                            <span className="px-3 font-black text-slate-900">{item.quantity}</span>
                            <button
                              onClick={() => updateQuantity(item.variantId, 1)}
                              className="p-1 hover:bg-slate-100 text-slate-600 transition"
                            >
                              <Plus className="w-3.5 h-3.5" />
                            </button>
                          </div>
                        </td>

                        <td className="p-3 font-black text-slate-900">
                          Rp {item.subtotal.toLocaleString('id-ID')}
                        </td>

                        <td className="p-3 pr-4 text-right">
                          <button
                            onClick={() => removeItem(item.variantId)}
                            className="p-1.5 text-slate-400 hover:text-rose-600 hover:bg-rose-50 rounded-lg transition"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

        </div>

        {/* Right Column: Customer Info & Payment Checkout */}
        <div className="space-y-4">
          <div className="bg-white border border-slate-200 rounded-2xl p-5 shadow-2xs space-y-4 sticky top-20">
            
            <h3 className="font-bold text-slate-900 text-sm border-b border-slate-100 pb-2">
              Detail Pembayaran & Pembeli
            </h3>

            {/* Customer Inputs */}
            <div className="space-y-3">
              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Nama Pembeli (Opsional)</label>
                <div className="relative">
                  <User className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
                  <input
                    type="text"
                    value={customerName}
                    onChange={(e) => setCustomerName(e.target.value)}
                    placeholder="cth: Ibu Siti / Pak Ahmad"
                    className="w-full pl-9 pr-3 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs font-semibold focus:ring-2 focus:ring-emerald-500"
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">No. WhatsApp Pembeli (Opsional)</label>
                <div className="relative">
                  <Phone className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
                  <input
                    type="text"
                    value={customerPhone}
                    onChange={(e) => setCustomerPhone(e.target.value)}
                    placeholder="cth: 085224503737 (Untuk Kirim Struk)"
                    className="w-full pl-9 pr-3 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs font-semibold focus:ring-2 focus:ring-emerald-500"
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Metode Pembayaran</label>
                <div className="grid grid-cols-3 gap-1.5">
                  {(['Tunai', 'QRIS', 'Transfer Bank'] as const).map(method => (
                    <button
                      type="button"
                      key={method}
                      onClick={() => setPaymentMethod(method)}
                      className={`py-2 px-1 text-[11px] font-bold rounded-xl transition ${
                        paymentMethod === method
                          ? 'bg-emerald-600 text-white shadow-xs'
                          : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
                      }`}
                    >
                      {method}
                    </button>
                  ))}
                </div>
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Potongan Diskon (Rp)</label>
                <input
                  type="number"
                  value={discount}
                  onChange={(e) => setDiscount(Number(e.target.value))}
                  min="0"
                  className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs font-bold focus:ring-2 focus:ring-emerald-500"
                />
              </div>
            </div>

            {/* Calculations Summary */}
            <div className="p-4 bg-slate-50 rounded-xl border border-slate-200/80 space-y-2 text-xs">
              <div className="flex justify-between text-slate-600">
                <span>Subtotal ({cart.reduce((a, c) => a + c.quantity, 0)} item):</span>
                <span className="font-bold text-slate-900">Rp {rawTotal.toLocaleString('id-ID')}</span>
              </div>

              {discount > 0 && (
                <div className="flex justify-between text-rose-600">
                  <span>Diskon:</span>
                  <span className="font-bold">-Rp {discount.toLocaleString('id-ID')}</span>
                </div>
              )}

              <div className="pt-2 border-t border-slate-200 flex justify-between items-center">
                <span className="font-extrabold text-slate-900 text-sm">TOTAL BAYAR:</span>
                <span className="text-xl font-black text-emerald-700">
                  Rp {finalTotal.toLocaleString('id-ID')}
                </span>
              </div>
            </div>

            {/* Submit Button */}
            <button
              onClick={handleSaveTransaction}
              disabled={cart.length === 0}
              className="w-full py-3 bg-emerald-600 hover:bg-emerald-700 disabled:bg-slate-300 text-white font-black text-sm rounded-xl shadow-lg transition flex items-center justify-center gap-2 active:scale-98"
            >
              <CheckCircle2 className="w-5 h-5" /> Simpan & Selesaikan Transaksi
            </button>

          </div>
        </div>

      </div>

      {/* Receipt Modal */}
      <ReceiptModal
        transaction={completedTransaction}
        isOpen={isReceiptOpen}
        onClose={() => setIsReceiptOpen(false)}
      />

    </div>
  );
};
