'use client';

import React, { useState } from 'react';
import { Trash2, Plus, Minus, User, UserPlus, X, ChevronDown, Percent } from 'lucide-react';
import { CartItem } from './posData';

interface Customer {
  id: string;
  name: string;
  phone: string;
  points: number;
}

interface CartPanelProps {
  cart: CartItem[];
  customer: Customer | null;
  customers: Customer[];
  onSelectCustomer: (c: Customer | null) => void;
  onUpdateQty: (productId: string, qty: number) => void;
  onUpdateDiscount: (productId: string, discount: number) => void;
  onRemove: (productId: string) => void;
  orderDiscount: number;
  onOrderDiscount: (d: number) => void;
  subtotal: number;
  vatAmount: number;
  grandTotal: number;
  orderDiscountAmt: number;
}

export default function CartPanel({
  cart,
  customer,
  customers,
  onSelectCustomer,
  onUpdateQty,
  onUpdateDiscount,
  onRemove,
  orderDiscount,
  onOrderDiscount,
  subtotal,
  vatAmount,
  grandTotal,
  orderDiscountAmt,
}: CartPanelProps) {
  const [customerSearch, setCustomerSearch] = useState('');
  const [customerDropOpen, setCustomerDropOpen] = useState(false);

  const filteredCustomers = customers.filter(
    (c) =>
      c.name.toLowerCase().includes(customerSearch.toLowerCase()) ||
      c.phone.includes(customerSearch)
  );

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3 border-b border-border bg-card flex-shrink-0">
        <h2 className="text-sm font-700 text-foreground">
          Current Sale
          {cart.length > 0 && (
            <span className="ml-2 w-5 h-5 inline-flex items-center justify-center rounded-full bg-primary text-white text-xs font-700">
              {cart.reduce((s, i) => s + i.qty, 0)}
            </span>
          )}
        </h2>
        {/* Customer selector */}
        <div className="relative">
          <button
            onClick={() => setCustomerDropOpen(!customerDropOpen)}
            className="flex items-center gap-1.5 px-2.5 py-1.5 bg-muted border border-border rounded-md text-xs font-600 text-foreground hover:bg-border transition-colors"
          >
            <User size={13} className="text-muted-foreground" />
            {customer ? customer.name : 'Walk-in'}
            <ChevronDown size={11} className="text-muted-foreground" />
          </button>
          {customerDropOpen && (
            <div className="absolute right-0 top-full mt-1 w-64 card-elevated rounded-lg shadow-modal z-20 fade-in overflow-hidden">
              <div className="p-2 border-b border-border">
                <input
                  type="text"
                  value={customerSearch}
                  onChange={(e) => setCustomerSearch(e.target.value)}
                  placeholder="Search customer…"
                  className="w-full h-8 px-2.5 text-xs bg-muted border border-border rounded outline-none placeholder:text-muted-foreground text-foreground"
                  autoFocus
                />
              </div>
              <ul className="max-h-48 overflow-y-auto scrollbar-thin py-1">
                <li>
                  <button
                    onClick={() => { onSelectCustomer(null); setCustomerDropOpen(false); setCustomerSearch(''); }}
                    className="w-full text-left px-3 py-2 text-xs hover:bg-muted transition-colors text-muted-foreground"
                  >
                    Walk-in Customer
                  </button>
                </li>
                {filteredCustomers.map((c) => (
                  <li key={c.id}>
                    <button
                      onClick={() => { onSelectCustomer(c); setCustomerDropOpen(false); setCustomerSearch(''); }}
                      className="w-full text-left px-3 py-2 hover:bg-muted transition-colors"
                    >
                      <p className="text-xs font-600 text-foreground">{c.name}</p>
                      <p className="text-xs text-muted-foreground">{c.phone} · {c.points} pts</p>
                    </button>
                  </li>
                ))}
                {filteredCustomers.length === 0 && (
                  <li className="px-3 py-2 text-xs text-muted-foreground">No customers found</li>
                )}
              </ul>
              <div className="border-t border-border p-2">
                <button className="w-full flex items-center gap-1.5 px-2.5 py-1.5 bg-primary/5 hover:bg-primary/10 rounded text-xs text-primary font-600 transition-colors">
                  <UserPlus size={12} />
                  Add New Customer
                </button>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Customer info bar */}
      {customer && (
        <div className="flex items-center justify-between px-4 py-2 bg-primary/5 border-b border-primary/10 flex-shrink-0">
          <div className="flex items-center gap-2">
            <div className="w-6 h-6 rounded-full bg-primary/20 flex items-center justify-center">
              <span className="text-xs font-700 text-primary">{customer.name[0]}</span>
            </div>
            <div>
              <p className="text-xs font-600 text-foreground">{customer.name}</p>
              <p className="text-xs text-muted-foreground">{customer.phone} · {customer.points} loyalty pts</p>
            </div>
          </div>
          <button
            onClick={() => onSelectCustomer(null)}
            className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
          >
            <X size={12} />
          </button>
        </div>
      )}

      {/* Cart items */}
      <div className="flex-1 overflow-y-auto scrollbar-thin">
        {cart.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-full text-center px-6">
            <div className="w-14 h-14 rounded-full bg-muted flex items-center justify-center mb-3">
              <span className="text-2xl">🛒</span>
            </div>
            <p className="text-sm font-600 text-foreground mb-1">Cart is empty</p>
            <p className="text-xs text-muted-foreground">Select products from the left panel to add them here</p>
          </div>
        ) : (
          <div className="divide-y divide-border">
            {/* Column headers */}
            <div className="grid grid-cols-12 px-4 py-2 bg-muted/30 text-xs font-600 uppercase tracking-wide text-muted-foreground">
              <span className="col-span-4">Product</span>
              <span className="col-span-2 text-center">Qty</span>
              <span className="col-span-2 text-right">Price</span>
              <span className="col-span-2 text-center">Disc%</span>
              <span className="col-span-1 text-right">Total</span>
              <span className="col-span-1" />
            </div>
            {cart.map((item) => {
              const lineTotal = item.price * item.qty;
              const discAmt = lineTotal * (item.discount / 100);
              const lineNet = lineTotal - discAmt;
              return (
                <div key={`cart-${item.productId}`} className="grid grid-cols-12 items-center px-4 py-2.5 hover:bg-muted/20 transition-colors group">
                  {/* Name */}
                  <div className="col-span-4 min-w-0">
                    <p className="text-xs font-600 text-foreground truncate leading-tight">{item.name}</p>
                    <p className="text-xs text-muted-foreground font-tabular">
                      KES {item.price.toLocaleString()}
                    </p>
                  </div>

                  {/* Qty stepper */}
                  <div className="col-span-2 flex items-center justify-center gap-1">
                    <button
                      onClick={() => onUpdateQty(item.productId, item.qty - 1)}
                      className="w-5 h-5 rounded flex items-center justify-center bg-muted hover:bg-border text-muted-foreground hover:text-foreground transition-colors"
                    >
                      <Minus size={10} />
                    </button>
                    <span className="text-xs font-700 text-foreground w-5 text-center font-tabular">{item.qty}</span>
                    <button
                      onClick={() => onUpdateQty(item.productId, item.qty + 1)}
                      className="w-5 h-5 rounded flex items-center justify-center bg-muted hover:bg-border text-muted-foreground hover:text-foreground transition-colors"
                    >
                      <Plus size={10} />
                    </button>
                  </div>

                  {/* Unit price */}
                  <div className="col-span-2 text-right">
                    <span className="text-xs font-tabular text-foreground">{item.price.toLocaleString()}</span>
                  </div>

                  {/* Discount % */}
                  <div className="col-span-2 flex items-center justify-center">
                    <div className="relative flex items-center">
                      <input
                        type="number"
                        min={0}
                        max={100}
                        value={item.discount || ''}
                        onChange={(e) => onUpdateDiscount(item.productId, parseFloat(e.target.value) || 0)}
                        placeholder="0"
                        className="w-10 h-6 text-xs text-center bg-muted border border-border rounded outline-none focus:border-primary font-tabular text-foreground"
                      />
                      <Percent size={9} className="absolute -right-3 text-muted-foreground" />
                    </div>
                  </div>

                  {/* Line total */}
                  <div className="col-span-1 text-right">
                    <span className={`text-xs font-700 font-tabular ${item.discount > 0 ? 'text-success' : 'text-foreground'}`}>
                      {lineNet.toLocaleString()}
                    </span>
                  </div>

                  {/* Remove */}
                  <div className="col-span-1 flex justify-end">
                    <button
                      onClick={() => onUpdateQty(item.productId, 0)}
                      className="p-1 rounded opacity-0 group-hover:opacity-100 hover:bg-danger-bg text-muted-foreground hover:text-danger transition-all"
                    >
                      <Trash2 size={11} />
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Order totals */}
      {cart.length > 0 && (
        <div className="border-t border-border bg-card flex-shrink-0 px-4 py-3 space-y-1.5">
          <div className="flex items-center justify-between text-xs text-muted-foreground">
            <span>Subtotal ({cart.reduce((s, i) => s + i.qty, 0)} items)</span>
            <span className="font-tabular font-600 text-foreground">KES {subtotal.toLocaleString()}</span>
          </div>

          {/* Order-level discount */}
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <span className="text-xs text-muted-foreground">Order Discount</span>
              <div className="relative flex items-center">
                <input
                  type="number"
                  min={0}
                  max={50}
                  value={orderDiscount || ''}
                  onChange={(e) => onOrderDiscount(parseFloat(e.target.value) || 0)}
                  placeholder="0"
                  className="w-10 h-5 text-xs text-center bg-muted border border-border rounded outline-none focus:border-primary font-tabular text-foreground"
                />
                <Percent size={9} className="absolute -right-3 text-muted-foreground" />
              </div>
            </div>
            <span className="text-xs font-tabular text-danger">
              {orderDiscountAmt > 0 ? `- KES ${orderDiscountAmt.toFixed(0)}` : 'KES 0'}
            </span>
          </div>

          <div className="flex items-center justify-between text-xs text-muted-foreground">
            <span>VAT (16% on taxable items)</span>
            <span className="font-tabular text-foreground">KES {vatAmount.toFixed(0)}</span>
          </div>

          <div className="h-px bg-border my-1" />

          <div className="flex items-center justify-between">
            <span className="text-sm font-700 text-foreground">Grand Total</span>
            <span className="text-lg font-800 text-primary font-tabular">
              KES {grandTotal.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 0 })}
            </span>
          </div>
        </div>
      )}
    </div>
  );
}