'use client';

import React, { useState, useRef } from 'react';
import { toast } from 'sonner';
import ProductBrowser from './ProductBrowser';
import CartPanel from './CartPanel';
import PaymentPanel from './PaymentPanel';
import { CartItem, Product, products as allProducts, mockCustomers } from './posData';
import { PauseCircle, RotateCcw } from 'lucide-react';

export default function POSTerminalClient() {
  const [cart, setCart] = useState<CartItem[]>([]);
  const [selectedCustomer, setSelectedCustomer] = useState<typeof mockCustomers[0] | null>(null);
  const [heldSales, setHeldSales] = useState<{ id: string; cart: CartItem[]; customer: typeof mockCustomers[0] | null }[]>([]);
  const [orderDiscount, setOrderDiscount] = useState(0);

  const addToCart = (product: Product) => {
    if (product.stock === 0) {
      toast.error(`${product.name} is out of stock`);
      return;
    }
    setCart((prev) => {
      const existing = prev.find((i) => i.productId === product.id);
      if (existing) {
        return prev.map((i) =>
          i.productId === product.id ? { ...i, qty: Math.min(i.qty + 1, product.stock) } : i
        );
      }
      return [
        ...prev,
        {
          productId: product.id,
          name: product.name,
          price: product.price,
          qty: 1,
          discount: 0,
          vatRate: product.vatRate,
        },
      ];
    });
    toast.success(`${product.name} added to cart`, { duration: 1200 });
  };

  const updateQty = (productId: string, qty: number) => {
    if (qty <= 0) {
      removeFromCart(productId);
      return;
    }
    const product = allProducts.find((p) => p.id === productId);
    if (product && qty > product.stock) {
      toast.warning(`Only ${product.stock} units available`);
      return;
    }
    setCart((prev) => prev.map((i) => (i.productId === productId ? { ...i, qty } : i)));
  };

  const updateDiscount = (productId: string, discount: number) => {
    setCart((prev) => prev.map((i) => (i.productId === productId ? { ...i, discount: Math.min(discount, 100) } : i)));
  };

  const removeFromCart = (productId: string) => {
    setCart((prev) => prev.filter((i) => i.productId !== productId));
  };

  const clearCart = () => {
    setCart([]);
    setSelectedCustomer(null);
    setOrderDiscount(0);
  };

  const holdSale = () => {
    if (cart.length === 0) {
      toast.warning('Cart is empty — nothing to hold');
      return;
    }
    const id = `hold-${Date.now()}`;
    setHeldSales((prev) => [...prev, { id, cart, customer: selectedCustomer }]);
    clearCart();
    toast.success('Sale put on hold — start a new transaction');
  };

  const recallSale = (id: string) => {
    const sale = heldSales.find((s) => s.id === id);
    if (!sale) return;
    if (cart.length > 0) {
      toast.warning('Clear current cart before recalling a held sale');
      return;
    }
    setCart(sale.cart);
    setSelectedCustomer(sale.customer);
    setHeldSales((prev) => prev.filter((s) => s.id !== id));
    toast.success('Held sale recalled');
  };

  // Totals
  const subtotal = cart.reduce((sum, item) => {
    const lineTotal = item.price * item.qty;
    const lineDiscount = lineTotal * (item.discount / 100);
    return sum + lineTotal - lineDiscount;
  }, 0);

  const orderDiscountAmt = subtotal * (orderDiscount / 100);
  const taxableAmount = subtotal - orderDiscountAmt;
  const vatAmount = cart.reduce((sum, item) => {
    if (item.vatRate === 0) return sum;
    const lineTotal = item.price * item.qty;
    const lineDiscount = lineTotal * (item.discount / 100);
    const lineNet = (lineTotal - lineDiscount) * (1 - orderDiscount / 100);
    return sum + lineNet * (item.vatRate / (100 + item.vatRate));
  }, 0);
  const grandTotal = taxableAmount;

  return (
    <div className="flex flex-col h-full bg-background">
      {/* POS Toolbar */}
      <div className="flex items-center justify-between px-4 py-2 bg-primary border-b border-primary/80">
        <div className="flex items-center gap-3">
          <span className="text-sm font-700 text-white">POS Terminal</span>
          <span className="text-xs text-white/60">Till #1 · Westlands · Cashier: A. Mwangi</span>
        </div>
        <div className="flex items-center gap-2">
          {heldSales.length > 0 && (
            <div className="flex items-center gap-1">
              {heldSales.map((s) => (
                <button
                  key={s.id}
                  onClick={() => recallSale(s.id)}
                  className="flex items-center gap-1 px-2.5 py-1 bg-white/20 hover:bg-white/30 rounded text-xs text-white font-600 transition-colors"
                >
                  <RotateCcw size={11} />
                  Recall
                </button>
              ))}
            </div>
          )}
          <button
            onClick={holdSale}
            className="flex items-center gap-1.5 px-3 py-1 bg-white/10 hover:bg-white/20 rounded text-xs text-white font-600 transition-colors"
          >
            <PauseCircle size={13} />
            Hold Sale
          </button>
          <button
            onClick={clearCart}
            className="flex items-center gap-1.5 px-3 py-1 bg-white/10 hover:bg-white/20 rounded text-xs text-white font-600 transition-colors"
          >
            <RotateCcw size={13} />
            New Sale
          </button>
        </div>
      </div>

      {/* 3-panel layout */}
      <div className="flex flex-1 min-h-0 overflow-hidden">
        {/* Left: Product Browser */}
        <div className="pos-panel-left border-r border-border overflow-hidden flex flex-col">
          <ProductBrowser onAddToCart={addToCart} />
        </div>

        {/* Center: Cart */}
        <div className="pos-panel-center border-r border-border overflow-hidden flex flex-col">
          <CartPanel
            cart={cart}
            customer={selectedCustomer}
            customers={mockCustomers}
            onSelectCustomer={setSelectedCustomer}
            onUpdateQty={updateQty}
            onUpdateDiscount={updateDiscount}
            onRemove={removeFromCart}
            orderDiscount={orderDiscount}
            onOrderDiscount={setOrderDiscount}
            subtotal={subtotal}
            vatAmount={vatAmount}
            grandTotal={grandTotal}
            orderDiscountAmt={orderDiscountAmt}
          />
        </div>

        {/* Right: Payment */}
        <div className="pos-panel-right overflow-hidden flex flex-col">
          <PaymentPanel
            grandTotal={grandTotal}
            cart={cart}
            customer={selectedCustomer}
            onComplete={clearCart}
          />
        </div>
      </div>
    </div>
  );
}