import { useEffect, useState, useRef } from 'react';
import { useReactToPrint } from 'react-to-print';
import api from '../services/api';
import toast from 'react-hot-toast';
import { formatCurrency } from '../utils/formatters';
import Modal from '../components/ui/Modal';
import Receipt from '../components/Receipt';
import { PlusIcon, MinusIcon, TrashIcon, MagnifyingGlassIcon, PrinterIcon, SignalIcon, XMarkIcon } from '@heroicons/react/24/outline';
import {
  isBluetoothSupported,
  isConnected as btIsConnected,
  getDeviceName,
  connect as btConnect,
  disconnect as btDisconnect,
  printReceipt as btPrintReceipt,
} from '../utils/bluetoothPrinter';

export default function POS() {
  const [products, setProducts] = useState([]);
  const [packages, setPackages] = useState([]);
  const [cart, setCart] = useState([]);
  const [search, setSearch] = useState('');
  const [tab, setTab] = useState('product');
  const [paymentModal, setPaymentModal] = useState(false);
  const [receiptModal, setReceiptModal] = useState(false);
  const [lastSale, setLastSale] = useState(null);
  const [payMethod, setPayMethod] = useState('tunai');
  const [amountPaid, setAmountPaid] = useState('');
  const [loading, setLoading] = useState(false);
  const [settings, setSettings] = useState(null);
  const [btName, setBtName] = useState(null);
  const [btPrinting, setBtPrinting] = useState(false);
  const receiptRef = useRef();

  useEffect(() => {
    api.get('/products/active').then(r => setProducts(r.data.data));
    api.get('/packages/active').then(r => setPackages(r.data.data));
    api.get('/settings').then(r => setSettings(r.data.data));
  }, []);

  const handlePrint = useReactToPrint({ content: () => receiptRef.current });

  async function handleBtConnect() {
    try {
      const name = await btConnect(() => {
        setBtName(null);
        toast('Printer Bluetooth terputus', { icon: '🔌' });
      });
      setBtName(name);
      toast.success(`Terhubung ke ${name}`);
    } catch (err) {
      if (err.name !== 'NotFoundError') toast.error(err.message);
    }
  }

  function handleBtDisconnect() {
    btDisconnect();
    setBtName(null);
    toast('Printer Bluetooth diputus', { icon: '🔵' });
  }

  async function handleBtPrint() {
    setBtPrinting(true);
    try {
      await btPrintReceipt(lastSale, settings);
      toast.success('Struk dicetak ke printer Bluetooth');
    } catch (err) {
      toast.error(err.message);
    } finally {
      setBtPrinting(false);
    }
  }

  const total = cart.reduce((s, i) => s + i.subtotal, 0);
  const change = payMethod === 'tunai' ? parseFloat(amountPaid || 0) - total : 0;

  const filtered = tab === 'product'
    ? products.filter(p => p.name.toLowerCase().includes(search.toLowerCase()))
    : packages.filter(p => p.name.toLowerCase().includes(search.toLowerCase()));

  function addToCart(item, type) {
    const key = `${type}-${item.id}`;
    setCart(prev => {
      const idx = prev.findIndex(c => c.key === key);
      if (idx >= 0) {
        const updated = [...prev];
        updated[idx] = { ...updated[idx], qty: updated[idx].qty + 1, subtotal: (updated[idx].qty + 1) * updated[idx].unit_price };
        return updated;
      }
      return [...prev, {
        key, item_type: type,
        product_id: type === 'product' ? item.id : null,
        package_id: type === 'package' ? item.id : null,
        name: item.name, qty: 1, unit_price: parseFloat(item.selling_price), subtotal: parseFloat(item.selling_price),
      }];
    });
  }

  function updateQty(key, delta) {
    setCart(prev => prev.map(c => {
      if (c.key !== key) return c;
      const qty = c.qty + delta;
      if (qty <= 0) return null;
      return { ...c, qty, subtotal: qty * c.unit_price };
    }).filter(Boolean));
  }

  function removeItem(key) { setCart(prev => prev.filter(c => c.key !== key)); }

  async function checkout() {
    if (payMethod === 'tunai' && parseFloat(amountPaid || 0) < total) {
      return toast.error('Uang bayar kurang dari total');
    }
    setLoading(true);
    try {
      const items = cart.map(c => ({
        item_type: c.item_type,
        product_id: c.product_id,
        package_id: c.package_id,
        qty: c.qty,
      }));
      const res = await api.post('/sales', { payment_method: payMethod, amount_paid: parseFloat(amountPaid) || total, items });
      setLastSale(res.data.data);
      setCart([]);
      setPaymentModal(false);
      setReceiptModal(true);
      setAmountPaid('');
      toast.success(`Transaksi berhasil! ${res.data.data.invoice_no}`);
    } catch {
      // handled by interceptor
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex flex-col lg:flex-row gap-4 h-full min-h-0">
      {/* Product panel */}
      <div className="flex-1 flex flex-col min-h-0">
        <div className="flex gap-2 mb-3">
          <div className="relative flex-1">
            <MagnifyingGlassIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input className="input pl-9" placeholder="Cari produk atau paket..." value={search} onChange={e => setSearch(e.target.value)} />
          </div>
          <div className="flex gap-1">
            {['product','package'].map(t => (
              <button key={t} onClick={() => setTab(t)}
                className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors ${tab === t ? 'bg-orange-500 text-white' : 'bg-white border text-gray-600 hover:bg-gray-50'}`}>
                {t === 'product' ? 'Produk' : 'Paket'}
              </button>
            ))}
          </div>
        </div>

        <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-4 gap-3 overflow-y-auto flex-1">
          {filtered.map(item => (
            <button key={item.id} onClick={() => addToCart(item, tab)}
              className="card p-3 text-left hover:border-orange-300 hover:shadow-md transition-all active:scale-95 group">
              <div className="text-2xl mb-2">{tab === 'product' ? '🛢️' : '📦'}</div>
              <p className="text-sm font-medium text-gray-800 leading-tight line-clamp-2">{item.name}</p>
              {tab === 'product' && <p className="text-xs text-gray-400 mt-0.5">Stok: {parseFloat(item.stock)} {item.unit}</p>}
              <p className="text-orange-500 font-bold text-sm mt-1">{formatCurrency(item.selling_price)}</p>
            </button>
          ))}
          {filtered.length === 0 && (
            <div className="col-span-full text-center py-12 text-gray-400 text-sm">Tidak ada hasil</div>
          )}
        </div>
      </div>

      {/* Cart panel */}
      <div className="w-full lg:w-80 xl:w-96 flex flex-col card">
        <div className="px-4 py-3 border-b font-semibold text-gray-800">
          Keranjang ({cart.length} item)
        </div>

        <div className="flex-1 overflow-y-auto divide-y divide-gray-100">
          {cart.length === 0 && (
            <div className="p-8 text-center text-gray-400 text-sm">Keranjang kosong</div>
          )}
          {cart.map(item => (
            <div key={item.key} className="px-4 py-3">
              <div className="flex justify-between items-start gap-2">
                <p className="text-sm font-medium text-gray-800 flex-1 leading-tight">{item.name}</p>
                <button onClick={() => removeItem(item.key)} className="text-red-400 hover:text-red-600 flex-shrink-0 p-0.5">
                  <TrashIcon className="w-4 h-4" />
                </button>
              </div>
              <div className="flex items-center justify-between mt-2">
                <div className="flex items-center gap-2">
                  <button onClick={() => updateQty(item.key, -1)} className="w-6 h-6 rounded-full bg-gray-100 hover:bg-gray-200 flex items-center justify-center">
                    <MinusIcon className="w-3 h-3" />
                  </button>
                  <span className="text-sm font-medium w-6 text-center">{item.qty}</span>
                  <button onClick={() => updateQty(item.key, 1)} className="w-6 h-6 rounded-full bg-orange-100 hover:bg-orange-200 text-orange-600 flex items-center justify-center">
                    <PlusIcon className="w-3 h-3" />
                  </button>
                </div>
                <span className="text-sm font-bold text-orange-600">{formatCurrency(item.subtotal)}</span>
              </div>
            </div>
          ))}
        </div>

        <div className="px-4 py-4 border-t space-y-3">
          <div className="flex justify-between text-base font-bold">
            <span>Total</span>
            <span className="text-orange-600">{formatCurrency(total)}</span>
          </div>

          {/* Bluetooth printer status */}
          {isBluetoothSupported() && (
            <div className={`flex items-center gap-2 rounded-lg px-3 py-2 text-xs ${btName ? 'bg-blue-50 border border-blue-200' : 'bg-gray-50 border border-gray-200'}`}>
              <SignalIcon className={`w-4 h-4 flex-shrink-0 ${btName ? 'text-blue-500' : 'text-gray-400'}`} />
              {btName ? (
                <>
                  <span className="flex-1 text-blue-700 font-medium truncate">{btName}</span>
                  <button onClick={handleBtDisconnect} className="text-gray-400 hover:text-red-500">
                    <XMarkIcon className="w-4 h-4" />
                  </button>
                </>
              ) : (
                <>
                  <span className="flex-1 text-gray-500">Printer Bluetooth</span>
                  <button onClick={handleBtConnect} className="text-blue-600 font-medium hover:underline">
                    Hubungkan
                  </button>
                </>
              )}
            </div>
          )}

          <div className="flex gap-2">
            <button onClick={() => setCart([])} className="btn-secondary flex-1 justify-center" disabled={!cart.length}>Batal</button>
            <button onClick={() => setPaymentModal(true)} className="btn-primary flex-1 justify-center" disabled={!cart.length}>Bayar</button>
          </div>
        </div>
      </div>

      {/* Payment Modal */}
      <Modal open={paymentModal} onClose={() => setPaymentModal(false)} title="Pembayaran" size="sm">
        <div className="space-y-4">
          <div>
            <p className="label">Metode Pembayaran</p>
            <div className="grid grid-cols-3 gap-2">
              {['tunai','transfer','qris'].map(m => (
                <button key={m} onClick={() => setPayMethod(m)}
                  className={`py-2 rounded-lg border text-sm font-medium capitalize transition-colors ${payMethod === m ? 'border-orange-500 bg-orange-50 text-orange-700' : 'border-gray-200 text-gray-600 hover:border-gray-300'}`}>
                  {m === 'tunai' ? 'Tunai' : m.toUpperCase()}
                </button>
              ))}
            </div>
          </div>

          <div className="bg-gray-50 rounded-lg p-3">
            <div className="flex justify-between text-lg font-bold">
              <span>Total</span>
              <span className="text-orange-600">{formatCurrency(total)}</span>
            </div>
          </div>

          {payMethod === 'tunai' && (
            <>
              <div>
                <label className="label">Uang Bayar</label>
                <input type="text" inputMode="numeric" className="input" placeholder="0"
                  value={amountPaid ? amountPaid.replace(/\B(?=(\d{3})+(?!\d))/g, '.') : ''}
                  onChange={e => setAmountPaid(e.target.value.replace(/\./g, '').replace(/\D/g, ''))}
                  autoFocus />
              </div>
              <div className="flex justify-between text-sm font-medium">
                <span className="text-gray-600">Kembalian</span>
                <span className={change >= 0 ? 'text-green-600 font-bold' : 'text-red-600 font-bold'}>{formatCurrency(change)}</span>
              </div>
            </>
          )}

          <div className="flex gap-2 pt-2">
            <button onClick={() => setPaymentModal(false)} className="btn-secondary flex-1 justify-center">Batal</button>
            <button onClick={checkout} disabled={loading || (payMethod === 'tunai' && parseFloat(amountPaid || 0) < total)}
              className="btn-primary flex-1 justify-center">
              {loading ? 'Proses...' : 'Konfirmasi'}
            </button>
          </div>
        </div>
      </Modal>

      {/* Receipt Modal */}
      <Modal open={receiptModal} onClose={() => setReceiptModal(false)} title="Struk Pembayaran" size="sm">
        <div className="flex flex-col items-center gap-4">
          <Receipt ref={receiptRef} sale={lastSale} settings={settings} />
          <div className="flex flex-col gap-2 w-full">
            {/* Bluetooth print button */}
            {isBluetoothSupported() && (
              btName ? (
                <button onClick={handleBtPrint} disabled={btPrinting}
                  className="w-full flex items-center justify-center gap-2 py-2 px-4 rounded-lg bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium disabled:opacity-50">
                  <SignalIcon className="w-4 h-4" />
                  {btPrinting ? 'Mencetak...' : `Cetak ke ${btName}`}
                </button>
              ) : (
                <button onClick={handleBtConnect}
                  className="w-full flex items-center justify-center gap-2 py-2 px-4 rounded-lg border-2 border-dashed border-blue-300 text-blue-600 text-sm font-medium hover:bg-blue-50">
                  <SignalIcon className="w-4 h-4" />
                  Hubungkan Printer Bluetooth
                </button>
              )
            )}
            <div className="flex gap-2">
              <button onClick={() => setReceiptModal(false)} className="btn-secondary flex-1 justify-center">Tutup</button>
              <button onClick={handlePrint} className="btn-primary flex-1 justify-center gap-2">
                <PrinterIcon className="w-4 h-4" /> Cetak Browser
              </button>
            </div>
          </div>
        </div>
      </Modal>
    </div>
  );
}
