import React, { useState, useEffect } from 'react';

function App() {
  const [products, setProducts] = useState<any[]>([]);
  const [filtered, setFiltered] = useState<any[]>([]);
  const [search, setSearch] = useState('');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadProducts();
  }, []);

  useEffect(() => {
    setFiltered(products.filter(p => p.name.toLowerCase().includes(search.toLowerCase())));
  }, [search, products]);

  const loadProducts = async () => {
    setLoading(true);
    try {
      const response = await fetch('/mcp/pipedrive_products_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ limit: 500 })
      });
      const data = await response.json();
      setProducts(data.data || []);
    } catch (error) {
      console.error('Failed to load products:', error);
    } finally {
      setLoading(false);
    }
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0 }).format(amount);
  };

  if (loading) {
    return <div className="loading">Loading products...</div>;
  }

  return (
    <div className="app">
      <header className="header">
        <h1>📦 Product Catalog</h1>
        <button onClick={loadProducts} className="refresh-btn">↻ Refresh</button>
      </header>

      <div className="controls">
        <input
          type="text"
          placeholder="Search products..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="search-input"
        />
        <div className="count-badge">{filtered.length} products</div>
      </div>

      <div className="product-grid">
        {filtered.map(product => (
          <div key={product.id} className="product-card">
            <div className="product-name">{product.name}</div>
            {product.code && <div className="product-code">SKU: {product.code}</div>}
            <div className="product-price">{formatCurrency(product.price || 0)}</div>
            {product.description && <div className="product-description">{product.description}</div>}
            {product.unit && <div className="product-unit">Unit: {product.unit}</div>}
          </div>
        ))}
      </div>
    </div>
  );
}

export default App;
