import { useState } from 'react';
import { Search } from 'lucide-react';
import { Header } from '@/components/Header';
import { ProductCard } from '@/components/ProductCard';
import { CartPanel } from '@/components/CartPanel';
import { CategoryTabs } from '@/components/CategoryTabs';
import { CheckoutModal } from '@/components/CheckoutModal';
import { SuccessModal } from '@/components/SuccessModal';
import { useProducts, useFavoriteProducts, useCategories, useToggleFavorite, useSearchProduct } from '@/hooks/useProducts';
import { useCartStore } from '@/store/cart';
import type { Product, Sale } from '@/types';

export function POSPage() {
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [isCheckoutOpen, setIsCheckoutOpen] = useState(false);
  const [completedSale, setCompletedSale] = useState<Sale | null>(null);

  const { data: categories } = useCategories();
  const { data: products, isLoading: productsLoading } = useProducts(
    selectedCategory && selectedCategory !== 'favorites' ? selectedCategory : undefined
  );
  const { data: favorites } = useFavoriteProducts();
  const toggleFavorite = useToggleFavorite();
  const searchProduct = useSearchProduct();
  const addItem = useCartStore((state) => state.addItem);

  const displayProducts = selectedCategory === 'favorites' ? favorites : products;

  const filteredProducts = displayProducts?.filter((product) =>
    product.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    product.barcode?.includes(searchQuery)
  );

  const handleSelectProduct = (product: Product) => {
    addItem(product);
  };

  const handleBarcodeSearch = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!searchQuery) return;

    try {
      const product = await searchProduct.mutateAsync(searchQuery);
      if (product) {
        addItem(product);
        setSearchQuery('');
      }
    } catch {
      // Product not found - will show filtered list instead
    }
  };

  const handleCheckoutSuccess = (sale: Sale) => {
    setIsCheckoutOpen(false);
    setCompletedSale(sale);
  };

  return (
    <div className="h-screen flex flex-col bg-gray-50">
      <Header />

      <div className="flex-1 flex overflow-hidden">
        {/* Products Panel */}
        <div className="flex-1 flex flex-col min-w-0">
          {/* Search bar */}
          <form onSubmit={handleBarcodeSearch} className="p-4 bg-white border-b">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                type="text"
                className="input pl-10"
                placeholder="Buscar producto o escanear codigo..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
              />
            </div>
          </form>

          {/* Category tabs */}
          <CategoryTabs
            categories={categories || []}
            selectedCategoryId={selectedCategory}
            onSelect={setSelectedCategory}
          />

          {/* Products grid */}
          <div className="flex-1 overflow-y-auto p-4">
            {productsLoading ? (
              <div className="flex items-center justify-center h-full">
                <div className="animate-spin w-8 h-8 border-4 border-primary-500 border-t-transparent rounded-full" />
              </div>
            ) : filteredProducts?.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-full text-gray-400">
                <Package className="w-16 h-16 mb-4" />
                <p>No se encontraron productos</p>
              </div>
            ) : (
              <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-3">
                {filteredProducts?.map((product) => (
                  <ProductCard
                    key={product.id}
                    product={product}
                    onSelect={handleSelectProduct}
                    onToggleFavorite={() => toggleFavorite.mutate(product.id)}
                  />
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Cart Panel - Hidden on mobile, shown on larger screens */}
        <div className="hidden lg:flex w-96 border-l bg-white flex-col">
          <CartPanel onCheckout={() => setIsCheckoutOpen(true)} />
        </div>
      </div>

      {/* Mobile Cart Button */}
      <MobileCartButton onCheckout={() => setIsCheckoutOpen(true)} />

      {/* Checkout Modal */}
      <CheckoutModal
        isOpen={isCheckoutOpen}
        onClose={() => setIsCheckoutOpen(false)}
        onSuccess={handleCheckoutSuccess}
      />

      {/* Success Modal */}
      <SuccessModal
        isOpen={!!completedSale}
        sale={completedSale}
        onClose={() => setCompletedSale(null)}
      />
    </div>
  );
}

function MobileCartButton({ onCheckout }: { onCheckout: () => void }) {
  const { itemCount, total } = useCartStore();

  if (itemCount === 0) return null;

  return (
    <div className="lg:hidden fixed bottom-0 left-0 right-0 p-4 bg-white border-t safe-bottom">
      <button className="btn-primary w-full btn-lg" onClick={onCheckout}>
        Cobrar ({itemCount}) - ${total.toFixed(2)}
      </button>
    </div>
  );
}

// Import for the empty state
import { Package } from 'lucide-react';
