'use client';

/**
 * Cart Component
 * Shopping cart for POS with item management - Modern cashier-friendly design
 */

import { Minus, Plus, X, ShoppingCart, Trash2, AlertTriangle, Scan, XCircle, Tag } from 'lucide-react';
import { formatCurrency } from '@/lib/utils/format';
import Badge from '@/components/ui/Badge';
import { Input, Button, Select } from '@/components/ui';

export default function Cart({
  items = [],
  onUpdateQuantity,
  onRemoveItem,
  subtotal = 0,
  tax = 0,
  discount = 0,
  total = 0,
  discountCode = '',
  onDiscountCodeChange = () => {},
  onApplyDiscount = () => {},
  discountError = '',
  appliedDiscount = null,
  onRemoveDiscount = () => {},
  onEnableRemovalMode = () => {}, // Callback to enable scan-to-remove mode
  // Scanner props
  barcodeInput = '',
  onBarcodeInputChange = () => {},
  onBarcodeSubmit = () => {},
  barcodeInputRef = null,
  isScanning = false,
  isRemovalMode = false,
  onCancelRemovalMode = () => {},
  // Per-item discount props
  itemDiscounts = {}, // Map of item_id -> available discounts
  onItemDiscountChange = () => {}, // Callback when item discount is selected
  // Cart-level discount props
  cartDiscounts = [], // Array of available cart-level discounts
  // Tax mode props removed - tax functionality removed from system
  mode = 'full', // 'full' | 'desktop' | 'drawer'
}) {
  
  // Calculate item total with discount
  const calculateItemTotal = (item) => {
    const baseTotal = item.quantity * item.unit_price;
    if (!item.discount_id || !item.discount) {
      return baseTotal;
    }
    
    const discount = item.discount;
    let discountAmount = 0;
    
    if (discount.discount_type === 'PERCENTAGE') {
      discountAmount = (baseTotal * discount.discount_value) / 100;
      if (discount.max_discount_amount) {
        discountAmount = Math.min(discountAmount, discount.max_discount_amount);
      }
    } else if (discount.discount_type === 'FIXED_AMOUNT') {
      discountAmount = Math.min(discount.discount_value, baseTotal);
    }
    
    return baseTotal - discountAmount;
  };
  
  // Get discount amount for an item
  const getItemDiscountAmount = (item) => {
    const baseTotal = item.quantity * item.unit_price;
    if (!item.discount_id || !item.discount) {
      return 0;
    }
    
    const discount = item.discount;
    let discountAmount = 0;
    
    if (discount.discount_type === 'PERCENTAGE') {
      discountAmount = (baseTotal * discount.discount_value) / 100;
      if (discount.max_discount_amount) {
        discountAmount = Math.min(discountAmount, discount.max_discount_amount);
      }
    } else if (discount.discount_type === 'FIXED_AMOUNT') {
      discountAmount = Math.min(discount.discount_value, baseTotal);
    }
    
    return discountAmount;
  };
  return (
    <div className="flex flex-col h-full min-h-0 bg-white dark:bg-gray-900 rounded-xl shadow-sm border border-gray-200 dark:border-gray-800 overflow-hidden">
      {/* Header (optional) */}
      {mode === 'full' && (
        <div className="px-4 py-3 border-b border-gray-200 dark:border-gray-800 bg-gradient-to-r from-emerald-600 to-teal-600">
          <div className="flex items-center justify-between">
            <h3 className="font-bold text-white text-base flex items-center gap-2">
              <ShoppingCart className="w-4 h-4" />
              Shopping Cart
            </h3>
            <span className="bg-white/20 text-white text-xs font-semibold px-2.5 py-1 rounded-full">
              {items.length} {items.length === 1 ? 'item' : 'items'}
            </span>
          </div>
        </div>
      )}

      {/* Scanner Section - Right below the green header */}
      <div
        className={`
          border-b border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900
          ${mode === 'drawer' ? 'px-3 py-2' : 'px-4 py-3'}
        `}
      >
        <form onSubmit={onBarcodeSubmit} className="space-y-2">
          <div className="flex gap-2">
            <div className="flex-1 relative">
              <Input
                ref={barcodeInputRef}
                type="text"
                placeholder={isRemovalMode ? "Scan UID to remove..." : "Scan UID/Barcode..."}
                value={barcodeInput}
                onChange={onBarcodeInputChange}
                disabled={isScanning}
                leftIcon={<Scan className={`w-4 h-4 ${isRemovalMode ? 'text-red-500' : 'text-gray-400'}`} />}
                autoFocus={false}
                className={`w-full transition-all ${
                  isRemovalMode 
                    ? 'border-red-500 ring-2 ring-red-500/20 bg-red-50 dark:bg-red-900/10 focus:border-red-500 focus:ring-red-500/30' 
                    : 'border-gray-300 dark:border-gray-700 focus:border-blue-500 focus:ring-blue-500/20'
                }`}
              />
            </div>
            <Button
              type="submit"
              variant={isRemovalMode ? "danger" : "primary"}
              disabled={!barcodeInput.trim() || isScanning}
              loading={isScanning}
              size="sm"
              className="px-4 min-w-[80px]"
            >
              {isRemovalMode ? 'Remove' : 'Scan'}
            </Button>
          </div>
          {isRemovalMode && (
            <div className="flex items-center justify-between px-3 py-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 bg-red-500 rounded-full animate-pulse"></div>
                <span className="text-xs text-red-700 dark:text-red-400 font-medium">
                  Removal Mode Active
                </span>
              </div>
              <button
                type="button"
                onClick={onCancelRemovalMode}
                className="p-1 text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 hover:bg-red-100 dark:hover:bg-red-900/30 rounded transition-colors"
                title="Cancel removal mode"
              >
                <XCircle className="w-4 h-4" />
              </button>
            </div>
          )}
        </form>
      </div>

      {/* Cart Items */}
      <div className={`flex-1 min-h-0 overflow-y-auto ${mode === 'drawer' ? 'p-3' : 'p-4'}`}>
        {items.length === 0 ? (
          <div className="h-full flex flex-col items-center justify-center text-gray-400 dark:text-gray-500">
            <ShoppingCart className="w-16 h-16 mb-4 opacity-30" />
            <p className="text-lg font-medium">Cart is empty</p>
            <p className="text-sm mt-1">Add products to get started</p>
          </div>
        ) : (
          <ul className="space-y-3">
            {items.map((item) => (
              <li
                key={item.id || item.product_id}
                className={`
                  bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700
                  transition-all duration-200 hover:shadow-sm
                  ${mode === 'drawer' ? 'p-2.5' : 'p-3'}
                `}
              >
                <div className="flex justify-between items-start mb-3">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <h4 className="font-semibold text-gray-900 dark:text-white truncate">
                        {item.product_name}
                      </h4>
                      {item.added_via === 'scan' && (
                        <Badge variant="info" size="sm" className="text-xs flex-shrink-0">
                          Scanned
                        </Badge>
                      )}
                      {item.added_via === 'manual' && (
                        <Badge variant="secondary" size="sm" className="text-xs flex-shrink-0">
                          Manual
                        </Badge>
                      )}
                    </div>
                    {mode !== 'drawer' && item.variant_name && (
                      <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                        {item.variant_name}
                      </p>
                    )}
                    {mode !== 'drawer' && (
                      <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                        {formatCurrency(item.unit_price)} each
                      </p>
                    )}
                    {/* Stock Warning Badge */}
                    {mode !== 'drawer' && item.stockWarning && (
                      <div className="mt-2 space-y-1">
                        {item.stockWarning.status === 'OUT_OF_STOCK' && (
                          <Badge variant="danger" size="sm" className="flex items-center gap-1 w-fit">
                            <AlertTriangle className="w-3 h-3" />
                            Out of Stock - Will Preorder
                          </Badge>
                        )}
                        {item.stockWarning.status === 'PARTIAL' && (
                          <div className="space-y-1">
                            <Badge variant="warning" size="sm" className="flex items-center gap-1 w-fit">
                              <AlertTriangle className="w-3 h-3" />
                              Partial Stock
                            </Badge>
                            <div className="text-xs text-gray-600 dark:text-gray-400 pl-1">
                              ✅ {item.stockWarning.available} available • 📋 {item.stockWarning.shortfall} preorder
                            </div>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                  <div className="flex items-center gap-1">
                    {/* For scanned items, show delete button that enables removal mode */}
                    {item.added_via === 'scan' ? (
                      <button
                        onClick={() => onEnableRemovalMode(item)}
                        className="p-1.5 text-orange-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
                        title="Delete by scanning UID"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    ) : (
                      <button
                        onClick={() => onRemoveItem(item)}
                        className="p-1.5 text-gray-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
                        title="Remove item"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    )}
                  </div>
                </div>

                {/* Discount Selector - Only show if product has available discounts */}
                {mode !== 'drawer' && itemDiscounts[item.id] && itemDiscounts[item.id].length > 0 && (
                  <div className="mt-2 mb-3">
                    <label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">
                      Discount
                    </label>
                    <select
                      value={item.discount_id || ''}
                      onChange={(e) => onItemDiscountChange(item, e.target.value ? parseInt(e.target.value) : null)}
                      className="w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    >
                      <option value="">No discount</option>
                      {itemDiscounts[item.id].map((disc) => (
                        <option key={disc.id} value={disc.id}>
                          {disc.name} {disc.discount_type === 'PERCENTAGE' ? `(${disc.discount_value}%)` : `(${formatCurrency(disc.discount_value)})`}
                        </option>
                      ))}
                    </select>
                    {item.discount && (
                      <div className="mt-1 text-xs text-green-600 dark:text-green-400 flex items-center gap-1">
                        <Tag className="w-3 h-3" />
                        <span>
                          {item.discount.discount_type === 'PERCENTAGE'
                            ? `${item.discount.discount_value}% off`
                            : `${formatCurrency(item.discount.discount_value)} off`}
                        </span>
                      </div>
                    )}
                  </div>
                )}

                <div className="flex items-center justify-between">
                  {/* Quantity Controls */}
                  <div className="flex items-center gap-2">
                    {item.added_via === 'scan' ? (
                      // Scanned items: show quantity and UID count, disable decrease
                      <div className="flex items-center gap-2">
                        <div className="flex items-center gap-1 bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 p-1">
                          <span className="w-10 text-center font-bold text-gray-900 dark:text-white">
                            {item.quantity}
                          </span>
                        </div>
                        <span className="text-xs text-gray-500 dark:text-gray-400">
                          {item.scanned_uids?.length || 0} UID{item.scanned_uids?.length !== 1 ? 's' : ''}
                        </span>
                      </div>
                    ) : (
                      // Manual items: normal quantity controls
                      <div className="flex items-center gap-1 bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 p-1">
                        <button
                          onClick={() => onUpdateQuantity(item, Math.max(0, item.quantity - 1))}
                          className="w-8 h-8 flex items-center justify-center rounded-lg text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 hover:text-red-500 transition-colors"
                        >
                          <Minus className="w-4 h-4" />
                        </button>
                        <span className="w-10 text-center font-bold text-gray-900 dark:text-white">
                          {item.quantity}
                        </span>
                        <button
                          onClick={() => onUpdateQuantity(item, item.quantity + 1)}
                          className="w-8 h-8 flex items-center justify-center rounded-lg text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 hover:text-green-500 transition-colors"
                        >
                          <Plus className="w-4 h-4" />
                        </button>
                      </div>
                    )}
                  </div>

                  {/* Item Total */}
                  <div className="text-right">
                    {getItemDiscountAmount(item) > 0 && (
                      <div className="text-xs text-gray-500 dark:text-gray-400 line-through mb-0.5">
                        {formatCurrency(item.quantity * item.unit_price)}
                      </div>
                    )}
                    <span className="text-lg font-bold text-gray-900 dark:text-white">
                      {formatCurrency(calculateItemTotal(item))}
                    </span>
                    {getItemDiscountAmount(item) > 0 && (
                      <div className="text-xs text-green-600 dark:text-green-400 mt-0.5">
                        -{formatCurrency(getItemDiscountAmount(item))}
                      </div>
                    )}
                  </div>
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>

      {/* Cart-Level Discount Select (hide in drawer mode to give more room for items) */}
      {mode !== 'drawer' && items.length > 0 && (
        <div className="px-4 py-3 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50">
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
            Cart Discount
          </label>
          {appliedDiscount ? (
            <div className="p-3 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
              <div className="flex items-center justify-between">
                <div className="flex-1">
                  <p className="text-sm font-medium text-green-700 dark:text-green-400">
                    ✓ {appliedDiscount.name} Applied
                  </p>
                  {appliedDiscount.discount_type === 'PERCENTAGE' && (
                    <p className="text-xs text-green-600 dark:text-green-500 mt-0.5">
                      {appliedDiscount.discount_value}% off
                    </p>
                  )}
                  {appliedDiscount.discount_type === 'FIXED_AMOUNT' && (
                    <p className="text-xs text-green-600 dark:text-green-500 mt-0.5">
                      {formatCurrency(appliedDiscount.discount_value)} off
                    </p>
                  )}
                </div>
                <button
                  onClick={onRemoveDiscount}
                  className="ml-2 text-red-500 hover:text-red-700 dark:hover:text-red-400 text-sm font-medium"
                >
                  Remove
                </button>
              </div>
            </div>
          ) : (
            <div className="flex gap-2">
              <select
                value={discountCode}
                onChange={(e) => {
                  const selectedCode = e.target.value;
                  onDiscountCodeChange(selectedCode);
                  // Clear error when selection changes
                  if (discountError) {
                    // Error will be cleared by parent component when discount is applied/removed
                  }
                }}
                className="flex-1 px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
              >
                <option value="">No discount</option>
                {cartDiscounts.map((disc) => (
                  <option key={disc.id} value={disc.code || disc.id.toString()}>
                    {disc.name} {disc.discount_type === 'PERCENTAGE' ? `(${disc.discount_value}%)` : `(${formatCurrency(disc.discount_value)})`} {disc.code ? `- ${disc.code}` : ''}
                  </option>
                ))}
              </select>
              <button
                onClick={onApplyDiscount}
                disabled={!discountCode.trim()}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-300 disabled:cursor-not-allowed dark:disabled:bg-gray-700 transition-colors font-medium whitespace-nowrap"
              >
                Apply
              </button>
            </div>
          )}
          {discountError && (
            <p className="mt-2 text-red-500 text-sm">{discountError}</p>
          )}
        </div>
      )}

      {/* Totals */}
      {mode !== 'drawer' && items.length > 0 && (
        <div className="px-4 py-4 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50 space-y-2.5">
          {/* Tax Mode Toggle removed - tax functionality removed from system */}
          
          <div className="flex justify-between text-sm">
            <span className="text-gray-600 dark:text-gray-400">Subtotal</span>
            <span className="font-medium text-gray-900 dark:text-white">{formatCurrency(subtotal)}</span>
          </div>
          {discount > 0 && (
            <div className="flex justify-between text-sm text-green-600 dark:text-green-400">
              <span>Discount</span>
              <span className="font-medium">-{formatCurrency(discount)}</span>
            </div>
          )}
          {/* Tax display removed - tax functionality removed from system */}
          <div className="h-px bg-gray-200 dark:bg-gray-700" />
          <div className="flex justify-between items-center">
            <span className="text-lg font-bold text-gray-900 dark:text-white">Total</span>
            <span className="text-2xl font-bold text-emerald-600 dark:text-emerald-400">
              {formatCurrency(total)}
            </span>
          </div>
        </div>
      )}
    </div>
  );
}
