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

const 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;
};

const useToast = () => {
  const [toasts, setToasts] = useState<Array<{ id: number; message: string; type: string }>>([]);
  const show = (message: string, type = 'info') => {
    const id = Date.now();
    setToasts((prev) => [...prev, { id, message, type }]);
    setTimeout(() => setToasts((prev) => prev.filter((t) => t.id !== id)), 3000);
  };
  return { toasts, show };
};

const mockProducts = [
  { 
    id: 'prod_1', 
    name: 'Pro Plan', 
    description: 'For growing teams', 
    active: true,
    prices: [
      { id: 'price_1', amount: 9900, currency: 'usd', interval: 'month' },
      { id: 'price_2', amount: 99000, currency: 'usd', interval: 'year' }
    ]
  },
  { 
    id: 'prod_2', 
    name: 'Enterprise Plan', 
    description: 'For large organizations', 
    active: true,
    prices: [
      { id: 'price_3', amount: 29900, currency: 'usd', interval: 'month' }
    ]
  },
  { 
    id: 'prod_3', 
    name: 'Starter Pack', 
    description: 'Perfect for individuals', 
    active: true,
    prices: [
      { id: 'price_4', amount: 2900, currency: 'usd', interval: 'month' },
      { id: 'price_5', amount: 29000, currency: 'usd', interval: 'year' }
    ]
  },
  { 
    id: 'prod_4', 
    name: 'Premium Add-on', 
    description: 'Extra features', 
    active: false,
    prices: [
      { id: 'price_6', amount: 1500, currency: 'usd', interval: 'month' }
    ]
  },
];

const App = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [activeFilter, setActiveFilter] = useState('all');
  const [isPending, startTransition] = useTransition();
  const { toasts, show } = useToast();

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredProducts = useMemo(() => {
    return mockProducts.filter((product) => {
      const matchesSearch =
        product.name.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        product.description.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesActive = 
        activeFilter === 'all' || 
        (activeFilter === 'active' && product.active) ||
        (activeFilter === 'inactive' && !product.active);
      return matchesSearch && matchesActive;
    });
  }, [debouncedSearch, activeFilter]);

  const stats = useMemo(() => {
    const totalProducts = mockProducts.length;
    const activeProducts = mockProducts.filter((p) => p.active).length;
    const totalPrices = mockProducts.reduce((sum, p) => sum + p.prices.length, 0);
    return { totalProducts, activeProducts, totalPrices };
  }, []);

  const handleFilterChange = (filter: string) => {
    startTransition(() => {
      setActiveFilter(filter);
      show(`Showing ${filter} products`, 'info');
    });
  };

  const formatAmount = (amount: number, currency: string) => {
    return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(amount / 100);
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Product Catalog</h1>
        <p className="subtitle">Manage products, prices, and pricing tiers</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Products</div>
          <div className="stat-value">{stats.totalProducts}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Active Products</div>
          <div className="stat-value stat-success">{stats.activeProducts}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Prices</div>
          <div className="stat-value stat-warning">{stats.totalPrices}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          className="search-input"
          placeholder="Search products..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        <div className="filter-buttons">
          {['all', 'active', 'inactive'].map((filter) => (
            <button
              key={filter}
              className={`filter-btn ${activeFilter === filter ? 'active' : ''}`}
              onClick={() => handleFilterChange(filter)}
            >
              {filter.charAt(0).toUpperCase() + filter.slice(1)}
            </button>
          ))}
        </div>
      </div>

      {isPending && <div className="loading-indicator">Filtering...</div>}

      <div className="product-grid">
        {filteredProducts.length === 0 ? (
          <div className="empty-state">
            <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <circle cx="12" cy="12" r="10" strokeWidth="2" />
              <line x1="12" y1="8" x2="12" y2="12" strokeWidth="2" />
              <line x1="12" y1="16" x2="12.01" y2="16" strokeWidth="2" />
            </svg>
            <h3>No products found</h3>
            <p>Try adjusting your search or filter</p>
          </div>
        ) : (
          filteredProducts.map((product) => (
            <div key={product.id} className="product-card">
              <div className="product-header">
                <h3>{product.name}</h3>
                <span className={`badge ${product.active ? 'badge-active' : 'badge-inactive'}`}>
                  {product.active ? 'Active' : 'Inactive'}
                </span>
              </div>
              <p className="product-description">{product.description}</p>
              <div className="product-meta">
                <span className="mono">{product.id}</span>
              </div>
              <div className="pricing-tiers">
                <h4>Pricing Tiers</h4>
                {product.prices.map((price) => (
                  <div key={price.id} className="price-tier">
                    <span className="price-amount">
                      {formatAmount(price.amount, price.currency)}
                    </span>
                    <span className="price-interval">/ {price.interval}</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>
  );
};

export default App;
