'use client';

/**
 * Product Grid Component
 * Displays products in a grid for POS selection - Modern cashier-friendly design
 */

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { productsAPI } from '@/lib/api';
import { LoadingSpinner } from '@/components/ui';
import { formatCurrency } from '@/lib/utils/format';
import { Search, Package, ShoppingBag } from 'lucide-react';

export default function ProductGrid({ onProductSelect, selectedCategoryId = null }) {
  const [searchQuery, setSearchQuery] = useState('');

  // Fetch products with prices and inventory
  const { data: productsData, isLoading: productsLoading } = useQuery({
    queryKey: ['products', selectedCategoryId, searchQuery, 'pos'], // Added 'pos' to key to differentiate from regular list
    queryFn: () => {
      // Always include prices and inventory for POS
      // POS only shows Finished Goods (FG) - Raw Materials (RM) should not be visible
      const params = {
        limit: 100,
        include: 'prices,inventory', // Request prices and inventory
        quantity: 1, // Quantity for pricing (can be adjusted per cart item later)
        product_type: 'FG', // Only show Finished Goods on POS
        sell_on_pos: 'true', // Ensure only sellable products are shown
        ...(selectedCategoryId && { category_id: selectedCategoryId }),
      };
      
      // When searching, still filter by category if selected
      if (searchQuery) {
        params.search = searchQuery;
      }
      
      return productsAPI.list(params);
    },
  });

  const products = productsData?.data?.products || productsData?.data || [];
  
  // Debug: Log first product to check inventory data
  if (products.length > 0 && process.env.NODE_ENV === 'development') {
    console.log('Sample product data:', {
      name: products[0].name,
      track_inventory: products[0].track_inventory,
      inventory: products[0].inventory,
      hasInventories: !!products[0].inventories,
    });
  }

  return (
    <div className="h-full flex flex-col bg-white dark:bg-gray-900 rounded-xl shadow-sm border border-gray-200 dark:border-gray-800 overflow-hidden">
      {/* Search Bar */}
      <div className="px-4 py-3 border-b border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50">
        <div className="relative">
          <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
          <input
            type="text"
            placeholder="Search products by name or SKU..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full pl-12 pr-4 py-3 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-xl text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
          />
        </div>
      </div>

      {/* Product Grid */}
      <div className="flex-1 overflow-y-auto p-4">
        {productsLoading ? (
          <div className="flex items-center justify-center h-64">
            <div className="text-center">
              <LoadingSpinner size="lg" />
              <p className="mt-4 text-gray-500 dark:text-gray-400">Loading products...</p>
            </div>
          </div>
        ) : products.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-64 text-gray-500 dark:text-gray-400">
            <Package className="w-16 h-16 mb-4 opacity-30" />
            <p className="text-lg font-medium">No products found</p>
            <p className="text-sm">Try adjusting your search or category filter</p>
          </div>
        ) : (
          <div className="flex flex-wrap gap-3 sm:gap-4">
            {products.map((product) => (
              <button
                key={product.id}
                onClick={() => onProductSelect(product)}
                className="group bg-white dark:bg-gray-800 border-2 border-gray-200 dark:border-gray-700 rounded-2xl p-4 text-left transition-all duration-200 hover:border-blue-500 dark:hover:border-blue-400 hover:shadow-xl hover:shadow-blue-500/10 hover:scale-[1.02] active:scale-[0.98] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 dark:focus:ring-offset-gray-900 flex-shrink-0"
                style={{ minWidth: '140px', maxWidth: '200px', flex: '1 1 auto' }}
              >
                {/* Product Image/Placeholder */}
                <div className="aspect-square bg-gradient-to-br from-gray-100 to-gray-200 dark:from-gray-700 dark:to-gray-800 rounded-xl mb-3 flex items-center justify-center overflow-hidden relative">
                  {product.image_url ? (
                    <img
                      src={product.image_url}
                      alt={product.name}
                      className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-110"
                    />
                  ) : (
                    <span className="text-4xl font-bold text-gray-300 dark:text-gray-600 group-hover:text-blue-400 transition-colors">
                      {product.name.charAt(0).toUpperCase()}
                    </span>
                  )}
                  {/* Hover overlay */}
                  <div className="absolute inset-0 bg-blue-600/0 group-hover:bg-blue-600/10 transition-colors duration-200 flex items-center justify-center">
                    <ShoppingBag className="w-8 h-8 text-white opacity-0 group-hover:opacity-100 transition-opacity duration-200 drop-shadow-lg" />
                  </div>
                </div>

                {/* Product Info */}
                <h3 className="font-semibold text-sm text-gray-900 dark:text-white truncate group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors">
                  {product.name}
                </h3>
                <p className="text-xs text-gray-500 dark:text-gray-400 mt-1 truncate">
                  {product.sku || 'No SKU'}
                </p>
                
                {/* Price & Stock Status */}
                <div className="mt-3 flex items-center justify-between">
                  {/* Show price or warning if missing */}
                  {product.price?.amount || product.selling_price ? (
                    <span className="text-lg font-bold text-blue-600 dark:text-blue-400">
                      {formatCurrency(
                        product.price?.amount || 
                        product.selling_price || 
                        0
                      )}
                    </span>
                  ) : (
                    <span className="text-sm font-medium text-amber-600 dark:text-amber-400 italic">
                      No price set
                    </span>
                  )}
                  <div className="flex flex-col items-end gap-1">
                    {/* Note: RM products are filtered out, only FG products should appear on POS */}
                    {/* Show inventory for FG products if tracked */}
                    {product.track_inventory && product.inventory?.available_qty !== null && product.inventory?.available_qty !== undefined && (
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
                        product.inventory.available_qty > 0
                          ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400'
                          : 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400'
                      }`}>
                        {product.inventory.available_qty > 0 
                          ? `${product.inventory.available_qty} in stock`
                          : 'Out of stock'
                        }
                      </span>
                    )}
                  </div>
                </div>
              </button>
            ))}
          </div>
        )}
      </div>

      {/* Footer with count */}
      <div className="px-4 py-2.5 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50">
        <p className="text-xs text-gray-500 dark:text-gray-400 text-center">
          Showing <span className="font-semibold text-gray-700 dark:text-gray-300">{products.length}</span> {products.length === 1 ? 'product' : 'products'}
        </p>
      </div>
    </div>
  );
}
