'use client';

import React, { useState, useEffect } from 'react';
import { Search, ScanBarcode, Minus, Plus, Trash2, ShoppingCart } from 'lucide-react';
import { showToast } from '@/components/toast';
import { ReceiptLayout } from '@/components/ReceiptLayout';

export default function POSPage() {
  const [products, setProducts] = useState<any[]>([]);
  const [cart, setCart] = useState<{product: any, qty: number}[]>([]);
  const [filter, setFilter] = useState('All');
  const [lastOrder, setLastOrder] = useState<any>(null);
  const [showReceiptModal, setShowReceiptModal] = useState(false);
  const [customerName, setCustomerName] = useState('');
  const [customerPhone, setCustomerPhone] = useState('');

  useEffect(() => {
    fetch('/api/products')
      .then(res => res.json())
      .then(data => {
        if(Array.isArray(data)) setProducts(data);
      })
      .catch(err => console.error(err));
  }, []);

  const addToCart = (product: any) => {
    setCart(prev => {
      const exists = prev.find(item => item.product.id === product.id);
      if (exists) {
        return prev.map(item => item.product.id === product.id ? { ...item, qty: item.qty + 1 } : item);
      }
      return [...prev, { product, qty: 1 }];
    });
    showToast(`Added ${product.name} to cart`);
  };

  const updateQty = (id: number, delta: number) => {
    setCart(prev => prev.map(item => {
      if (item.product.id === id) {
        const newQty = Math.max(1, item.qty + delta);
        return { ...item, qty: newQty };
      }
      return item;
    }));
  };

  const removeFromCart = (id: number) => {
    setCart(prev => prev.filter(item => item.product.id !== id));
  };

  const handleCheckout = async () => {
    if (cart.length === 0) return;
    
    const items = cart.map(item => ({
      product_id: item.product.id,
      quantity: item.qty,
      unit_price: item.product.price,
      cost_price: item.product.cost_price
    }));

    try {
      const res = await fetch('/api/sales', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
          total_amount: total, 
          items, 
          customer_name: customerName, 
          customer_phone: customerPhone 
        })
      });
      if (res.ok) {
        const saleData = await res.json();
        showToast('Order Placed Successfully!', 'success');
        
        // Save order for receipt printing
        setLastOrder({
          id: saleData.sale_id || Math.floor(Math.random() * 10000), // fallback if backend doesn't return id
          items: [...cart],
          total: total,
          customer_name: customerName,
          customer_phone: customerPhone,
          date: new Date().toLocaleString()
        });
        
        setCart([]); // clear cart
        setCustomerName('');
        setCustomerPhone('');
        
        // Refresh products to show updated stock
        const freshProducts = await fetch('/api/products').then(r => r.json());
        if(Array.isArray(freshProducts)) setProducts(freshProducts);

        // Show the receipt preview modal
        setShowReceiptModal(true);

      } else {
        showToast('Failed to place order', 'error');
      }
    } catch (e) {
      showToast('Failed to place order', 'error');
    }
  };

  const total = cart.reduce((sum, item) => sum + (item.product.price * item.qty), 0);
  
  const displayedProducts = filter === 'All' 
    ? products 
    : products.filter(p => p.type.toLowerCase() === filter.toLowerCase());

  return (
    <div className="pos-layout">
      {/* Products Area */}
      <div className="pos-products">
        <h1 style={{ marginBottom: '0.25rem' }}>POS System</h1>
        <p style={{ marginBottom: '2rem' }}>Experience a seamless purchasing experience with our intuitive cashier interface.</p>
        
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
          <h3>List Product</h3>
          <div style={{ display: 'flex', gap: '1rem' }}>
            <button style={{ background: 'var(--panel-bg)', border: '1px solid var(--panel-border)' }}><ScanBarcode size={18} /> Scan Barcode</button>
            <div style={{ position: 'relative' }}>
              <Search size={18} style={{ position: 'absolute', left: '10px', top: '50%', transform: 'translateY(-50%)', color: 'var(--text-muted)' }} />
              <input type="text" placeholder="Search..." style={{ paddingLeft: '2.5rem', width: '250px' }} />
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', gap: '0.5rem', marginBottom: '2rem', flexWrap: 'wrap' }}>
          <button className={filter === 'All' ? 'primary' : ''} style={filter !== 'All' ? { borderRadius: '2rem', background: 'var(--panel-bg)', color: 'var(--text-muted)' } : { borderRadius: '2rem'}} onClick={() => setFilter('All')}>All Products</button>
          <button className={filter === 'Steel' ? 'primary' : ''} style={filter !== 'Steel' ? { borderRadius: '2rem', background: 'var(--panel-bg)', color: 'var(--text-muted)' } : { borderRadius: '2rem'}} onClick={() => setFilter('Steel')}>Steel</button>
          <button className={filter === 'Cement' ? 'primary' : ''} style={filter !== 'Cement' ? { borderRadius: '2rem', background: 'var(--panel-bg)', color: 'var(--text-muted)' } : { borderRadius: '2rem'}} onClick={() => setFilter('Cement')}>Cement</button>
        </div>

        {products.length === 0 ? (
           <p style={{ color: 'var(--text-muted)' }}>No products in database. Please add products from the Inventory tab first.</p>
        ) : (
          <div className="grid grid-3">
            {displayedProducts.map(product => (
              <div key={product.id} className="panel" style={{ padding: '1rem', display: 'flex', flexDirection: 'column' }}>
                <div style={{ background: 'var(--bg-color)', borderRadius: '0.5rem', height: '140px', marginBottom: '1rem', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-muted)' }}>
                  <span style={{textTransform:'capitalize'}}>{product.type} Image</span>
                </div>
                <div style={{ fontSize: '0.8rem', color: 'var(--text-muted)', marginBottom: '0.25rem', textTransform:'capitalize' }}>{product.type}</div>
                <h4 style={{ marginBottom: '0.5rem', fontSize: '1rem' }}>{product.name}</h4>
                <div style={{ fontSize: '0.875rem', color: 'var(--text-muted)', marginBottom: '1rem' }}>Stock: {product.stock_quantity} {product.unit}</div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 'auto' }}>
                  <span style={{ fontWeight: 'bold', fontSize: '1.1rem' }}>Rs {product.price}</span>
                  <button onClick={() => addToCart(product)} style={{ padding: '0.5rem', borderRadius: '50%' }}>
                    <ShoppingCart size={16} />
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Cart Sidebar */}
      <div className="panel pos-cart">
        <h2 style={{ paddingBottom: '1rem', borderBottom: '1px solid var(--panel-border)', marginBottom: '1rem' }}>Order Details</h2>
        <div style={{ fontSize: '0.875rem', color: 'var(--text-muted)', marginBottom: '1rem' }}>{cart.length} Items Selected</div>
        
        <div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: '1rem', paddingRight: '0.5rem' }}>
          {cart.map(item => (
            <div key={item.product.id} style={{ display: 'flex', gap: '1rem', alignItems: 'center' }}>
              <div style={{ width: '60px', height: '60px', borderRadius: '0.5rem', overflow: 'hidden', background: 'var(--bg-color)', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '0.7rem', color: 'var(--text-muted)' }}>
                {item.product.type}
              </div>
              <div style={{ flex: 1, overflow: 'hidden' }}>
                <div style={{ fontWeight: '600', fontSize: '0.9rem', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }}>{item.product.name}</div>
                <div style={{ color: 'var(--text-muted)', fontSize: '0.8rem' }}>Rs {item.product.price}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginTop: '0.5rem' }}>
                  <button onClick={() => updateQty(item.product.id, -1)} style={{ padding: '0.25rem', background: 'var(--bg-color)', border: '1px solid var(--panel-border)', borderRadius: '0.25rem' }}><Minus size={14}/></button>
                  <span style={{ fontSize: '0.9rem', width: '20px', textAlign: 'center' }}>{item.qty}</span>
                  <button onClick={() => updateQty(item.product.id, 1)} style={{ padding: '0.25rem', background: 'var(--bg-color)', border: '1px solid var(--panel-border)', borderRadius: '0.25rem' }}><Plus size={14}/></button>
                </div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontWeight: 'bold' }}>Rs {item.product.price * item.qty}</div>
                <button onClick={() => removeFromCart(item.product.id)} style={{ padding: '0.25rem', background: 'transparent', color: 'var(--danger)', marginTop: '0.5rem' }}><Trash2 size={16}/></button>
              </div>
            </div>
          ))}
          {cart.length === 0 && <div style={{ textAlign: 'center', color: 'var(--text-muted)', marginTop: '2rem' }}>Cart is empty</div>}
        </div>

        <div style={{ borderTop: '1px solid var(--panel-border)', paddingTop: '1rem', marginTop: '1rem' }}>
          
          <div style={{ marginBottom: '1rem' }}>
            <label style={{ display: 'block', fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '0.25rem' }}>Customer Name (Optional)</label>
            <input type="text" value={customerName} onChange={e => setCustomerName(e.target.value)} placeholder="e.g. John Doe" style={{ padding: '0.4rem 0.75rem', fontSize: '0.9rem' }} />
          </div>
          <div style={{ marginBottom: '1rem' }}>
            <label style={{ display: 'block', fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '0.25rem' }}>Customer Phone (Optional)</label>
            <input type="text" value={customerPhone} onChange={e => setCustomerPhone(e.target.value)} placeholder="e.g. 0300 1234567" style={{ padding: '0.4rem 0.75rem', fontSize: '0.9rem' }} />
          </div>

          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>
            <span>Sub Total</span>
            <span style={{ color: 'var(--text-main)', fontWeight: '500' }}>Rs {total}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1rem', color: 'var(--text-muted)' }}>
            <span>Discount</span>
            <span style={{ color: 'var(--text-main)', fontWeight: '500' }}>Rs 0</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1.5rem', fontSize: '1.25rem', fontWeight: 'bold' }}>
            <span>Total</span>
            <span style={{ color: 'var(--accent)' }}>Rs {total}</span>
          </div>
          <button className="primary" style={{ width: '100%', padding: '1rem', fontSize: '1.1rem', borderRadius: '0.5rem' }} onClick={handleCheckout} disabled={cart.length === 0}>
            Place Order
          </button>
        </div>
      </div>

      {/* Receipt Modal Preview */}
      {showReceiptModal && lastOrder && (
        <div className="print-hide" style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 9999 }}>
          <div style={{ background: 'var(--panel-bg)', padding: '2rem', borderRadius: '1rem', display: 'flex', flexDirection: 'column', alignItems: 'center', boxShadow: '0 10px 25px rgba(0,0,0,0.2)' }}>
            <h2 style={{ marginBottom: '1.5rem' }}>Order Completed!</h2>
            
            {/* Visual preview identical to print */}
            <div style={{ border: '1px solid #ccc', marginBottom: '1.5rem', boxShadow: '0 5px 15px rgba(0,0,0,0.1)' }}>
              <ReceiptLayout order={lastOrder} />
            </div>

            <div style={{ display: 'flex', gap: '1rem', width: '100%' }}>
              <button className="primary" style={{ flex: 1 }} onClick={() => window.print()}>Print Receipt</button>
              <button style={{ flex: 1, background: 'var(--bg-color)', border: '1px solid var(--panel-border)' }} onClick={() => setShowReceiptModal(false)}>Close</button>
            </div>
          </div>
        </div>
      )}

      {/* Thermal Receipt Print Layout (Hidden on screen, shown on print) */}
      {lastOrder && (
        <div className="print-receipt" style={{ display: 'none' }}>
          <ReceiptLayout order={lastOrder} />
        </div>
      )}
    </div>
  );
}
