import React, { useState, useMemo, useTransition, useCallback, useEffect } from 'react';

function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(handler);
  }, [value, delay]);

  return debouncedValue;
}

type Toast = { id: number; message: string; type: 'success' | 'error' };

function useToast() {
  const [toasts, setToasts] = useState<Toast[]>([]);

  const showToast = useCallback((message: string, type: 'success' | 'error' = 'success') => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message, type }]);
    setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3000);
  }, []);

  return { toasts, showToast };
}

type Product = {
  id: string;
  title: string;
  vendor: string;
  price: number;
  inventory: number;
  variants: number;
  status: 'active' | 'draft';
  image: string;
};

const mockProducts: Product[] = [
  { id: 'p1', title: 'Classic T-Shirt', vendor: 'Acme Apparel', price: 24.99, inventory: 150, variants: 3, status: 'active', image: '👕' },
  { id: 'p2', title: 'Running Shoes', vendor: 'SportCo', price: 89.99, inventory: 45, variants: 5, status: 'active', image: '👟' },
  { id: 'p3', title: 'Wireless Headphones', vendor: 'AudioTech', price: 129.99, inventory: 32, variants: 2, status: 'active', image: '🎧' },
  { id: 'p4', title: 'Yoga Mat', vendor: 'FitLife', price: 34.99, inventory: 78, variants: 4, status: 'active', image: '🧘' },
  { id: 'p5', title: 'Coffee Mug Set', vendor: 'HomeGoods', price: 19.99, inventory: 200, variants: 3, status: 'draft', image: '☕' },
  { id: 'p6', title: 'Laptop Backpack', vendor: 'TechGear', price: 59.99, inventory: 12, variants: 2, status: 'active', image: '🎒' },
  { id: 'p7', title: 'Smart Watch', vendor: 'WearTech', price: 249.99, inventory: 8, variants: 3, status: 'active', image: '⌚' },
  { id: 'p8', title: 'Desk Plant', vendor: 'GreenSpace', price: 14.99, inventory: 120, variants: 5, status: 'active', image: '🪴' },
];

export default function App() {
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'draft'>('all');
  const [isPending, startTransition] = useTransition();
  const { toasts, showToast } = useToast();

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredProducts = useMemo(() => {
    return mockProducts.filter(p => {
      const matchesSearch = p.title.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
                           p.vendor.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesStatus = statusFilter === 'all' || p.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [debouncedSearch, statusFilter]);

  const stats = useMemo(() => ({
    total: mockProducts.length,
    active: mockProducts.filter(p => p.status === 'active').length,
    totalValue: mockProducts.reduce((sum, p) => sum + (p.price * p.inventory), 0),
    lowStock: mockProducts.filter(p => p.inventory < 20).length,
  }), []);

  const handleSearch = (value: string) => {
    startTransition(() => setSearchQuery(value));
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Product Catalog</h1>
        <p>Browse and manage your product inventory</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Products</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Active</div>
          <div className="stat-value">{stats.active}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Inventory Value</div>
          <div className="stat-value">${stats.totalValue.toLocaleString()}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Low Stock</div>
          <div className="stat-value" style={{ color: stats.lowStock > 0 ? '#f59e0b' : 'inherit' }}>
            {stats.lowStock}
          </div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          placeholder="Search products..."
          value={searchQuery}
          onChange={(e) => handleSearch(e.target.value)}
          className="search-input"
        />
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value as any)}
          className="filter-select"
        >
          <option value="all">All Status</option>
          <option value="active">Active</option>
          <option value="draft">Draft</option>
        </select>
      </div>

      {filteredProducts.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">📦</div>
          <h3>No products found</h3>
          <p>Try adjusting your search or filters</p>
        </div>
      ) : (
        <div className="data-grid" style={{ opacity: isPending ? 0.6 : 1 }}>
          {filteredProducts.map(product => (
            <div key={product.id} className="data-card">
              <div className="product-image">{product.image}</div>
              <div className="data-card-content">
                <h3>{product.title}</h3>
                <p className="product-vendor">{product.vendor}</p>
                <div className="product-details">
                  <span className="product-price">${product.price}</span>
                  <span className={`status-badge status-${product.status}`}>{product.status}</span>
                </div>
                <div className="product-meta">
                  <span>Stock: {product.inventory}</span>
                  <span>{product.variants} variants</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      <div className="toast-container">
        {toasts.map(toast => (
          <div key={toast.id} className={`toast toast-${toast.type}`}>
            {toast.message}
          </div>
        ))}
      </div>
    </div>
  );
}
