'use client';

import React, { useState, useRef } from 'react';
import { Search, Barcode, Plus } from 'lucide-react';
import { Product, products, categories } from './posData';

interface ProductBrowserProps {
  onAddToCart: (product: Product) => void;
}

export default function ProductBrowser({ onAddToCart }: ProductBrowserProps) {
  const [activeCategory, setActiveCategory] = useState('cat-all');
  const [search, setSearch] = useState('');
  const scanRef = useRef<HTMLInputElement>(null);

  const filtered = products.filter((p) => {
    const matchesCat = activeCategory === 'cat-all' || p.category === categories.find((c) => c.id === activeCategory)?.label;
    const matchesSearch =
      !search ||
      p.name.toLowerCase().includes(search.toLowerCase()) ||
      p.sku.toLowerCase().includes(search.toLowerCase()) ||
      p.barcode.includes(search);
    return matchesCat && matchesSearch;
  });

  // Barcode scan handler — Backend: trigger barcode lookup API
  const handleBarcodeKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      const barcode = (e.target as HTMLInputElement).value.trim();
      const product = products.find((p) => p.barcode === barcode);
      if (product) {
        onAddToCart(product);
        setSearch('');
      }
    }
  };

  const stockBadge = (stock: number) => {
    if (stock === 0) return { label: 'Out of Stock', cls: 'badge-danger' };
    if (stock <= 5) return { label: `${stock} left`, cls: 'badge-warning' };
    return { label: `${stock} in stock`, cls: 'badge-neutral' };
  };

  return (
    <>
      {/* Search & scan */}
      <div className="p-3 border-b border-border space-y-2 bg-card flex-shrink-0">
        <div className="flex items-center gap-2 bg-muted border border-border rounded-md px-3 h-9">
          <Search size={14} className="text-muted-foreground flex-shrink-0" />
          <input
            ref={scanRef}
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            onKeyDown={handleBarcodeKeyDown}
            placeholder="Search or scan barcode…"
            className="bg-transparent text-sm text-foreground placeholder:text-muted-foreground outline-none flex-1"
          />
          <Barcode size={14} className="text-muted-foreground flex-shrink-0" />
        </div>

        {/* Category tabs */}
        <div className="flex gap-1 overflow-x-auto scrollbar-thin pb-0.5">
          {categories.map((cat) => (
            <button
              key={cat.id}
              onClick={() => setActiveCategory(cat.id)}
              className={`flex-shrink-0 px-2.5 py-1 rounded-md text-xs font-600 transition-colors whitespace-nowrap ${
                activeCategory === cat.id
                  ? 'bg-primary text-white' :'bg-muted text-muted-foreground hover:bg-border hover:text-foreground'
              }`}
            >
              {cat.label}
            </button>
          ))}
        </div>
      </div>

      {/* Product grid */}
      <div className="flex-1 overflow-y-auto scrollbar-thin p-3">
        {filtered.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-40 text-center">
            <Search size={28} className="text-muted-foreground mb-2" />
            <p className="text-sm font-600 text-foreground">No products found</p>
            <p className="text-xs text-muted-foreground mt-1">Try a different search or category</p>
          </div>
        ) : (
          <div className="grid grid-cols-2 gap-2">
            {filtered.map((product) => {
              const badge = stockBadge(product.stock);
              const outOfStock = product.stock === 0;
              return (
                <button
                  key={product.id}
                  onClick={() => onAddToCart(product)}
                  disabled={outOfStock}
                  className={`product-tile-hover relative text-left rounded-lg border p-3 transition-all duration-150 flex flex-col gap-1.5 ${
                    outOfStock
                      ? 'border-border bg-muted/30 opacity-60 cursor-not-allowed' :'border-border bg-card hover:border-primary/40 cursor-pointer'
                  }`}
                >
                  {/* Stock badge */}
                  <span className={`absolute top-2 right-2 text-xs px-1.5 py-0.5 rounded-full font-600 ${badge.cls}`}>
                    {badge.label}
                  </span>

                  {/* Product icon placeholder */}
                  <div className="w-10 h-10 rounded-lg bg-primary/8 flex items-center justify-center mb-0.5">
                    <span className="text-lg">{outOfStock ? '⚠️' : '📦'}</span>
                  </div>

                  <p className="text-xs font-700 text-foreground leading-tight pr-12">{product.name}</p>
                  <p className="text-xs text-muted-foreground font-mono">{product.sku}</p>

                  <div className="flex items-center justify-between mt-1">
                    <span className="text-sm font-800 text-primary font-tabular">
                      KES {product.price.toLocaleString()}
                    </span>
                    {!outOfStock && (
                      <span className="w-6 h-6 rounded-full bg-primary flex items-center justify-center">
                        <Plus size={13} className="text-white" />
                      </span>
                    )}
                  </div>
                </button>
              );
            })}
          </div>
        )}
      </div>

      {/* Footer count */}
      <div className="px-3 py-2 border-t border-border bg-muted/30 flex-shrink-0">
        <p className="text-xs text-muted-foreground">
          {filtered.length} product{filtered.length !== 1 ? 's' : ''} shown
          {search && ` for "${search}"`}
        </p>
      </div>
    </>
  );
}