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

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

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

  return debouncedValue;
};

const useToast = () => {
  const [toast, setToast] = useState<string | null>(null);

  const showToast = (message: string) => {
    setToast(message);
    setTimeout(() => setToast(null), 3000);
  };

  return { toast, showToast };
};

const mockItems = [
  { id: 'ITM001', name: 'Web Design Service', type: 'Service', price: 150.00, qty: 0, description: 'Hourly web design service' },
  { id: 'ITM002', name: 'Premium Software License', type: 'Product', price: 499.00, qty: 25, description: 'Annual software subscription' },
  { id: 'ITM003', name: 'Consulting - Strategy', type: 'Service', price: 250.00, qty: 0, description: 'Business strategy consulting' },
  { id: 'ITM004', name: 'Office Chair Pro', type: 'Product', price: 399.99, qty: 12, description: 'Ergonomic office chair' },
  { id: 'ITM005', name: 'Cloud Hosting', type: 'Service', price: 99.00, qty: 0, description: 'Monthly cloud hosting' },
  { id: 'ITM006', name: 'Laptop - Business Edition', type: 'Product', price: 1299.00, qty: 8, description: 'Business laptop' },
];

type Item = typeof mockItems[0];

const App: React.FC = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [filterType, setFilterType] = useState<string>('all');
  const [isPending, startTransition] = useTransition();
  const { toast, showToast } = useToast();

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredItems = useMemo(() => {
    return mockItems.filter((item) => {
      const matchesSearch =
        item.name.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        item.description.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        item.id.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesFilter = filterType === 'all' || item.type === filterType;
      return matchesSearch && matchesFilter;
    });
  }, [debouncedSearch, filterType]);

  const stats = useMemo(() => {
    const total = mockItems.length;
    const products = mockItems.filter(i => i.type === 'Product').length;
    const services = mockItems.filter(i => i.type === 'Service').length;
    const totalValue = mockItems.reduce((sum, i) => sum + (i.price * (i.qty || 1)), 0);
    return { total, products, services, totalValue };
  }, []);

  const handleFilterChange = (type: string) => {
    startTransition(() => {
      setFilterType(type);
      showToast(`Filter: ${type === 'all' ? 'All Items' : type + 's'}`);
    });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Item Catalog</h1>
        <p>Products and services inventory with pricing</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Items</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card stat-success">
          <div className="stat-label">Products</div>
          <div className="stat-value">{stats.products}</div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-label">Services</div>
          <div className="stat-value">{stats.services}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Catalog Value</div>
          <div className="stat-value">${stats.totalValue.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          className="search-input"
          placeholder="Search by name, description, or ID..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        <div className="filter-buttons">
          {['all', 'Product', 'Service'].map((type) => (
            <button
              key={type}
              className={`filter-btn ${filterType === type ? 'active' : ''}`}
              onClick={() => handleFilterChange(type)}
            >
              {type === 'all' ? 'All' : type + 's'}
            </button>
          ))}
        </div>
      </div>

      {filteredItems.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">📦</div>
          <h3>No items found</h3>
          <p>Try adjusting your search or filters</p>
        </div>
      ) : (
        <div className={`data-grid ${isPending ? 'loading' : ''}`}>
          <table>
            <thead>
              <tr>
                <th>Item ID</th>
                <th>Name</th>
                <th>Type</th>
                <th>Description</th>
                <th>Price</th>
                <th>Qty</th>
              </tr>
            </thead>
            <tbody>
              {filteredItems.map((item) => (
                <tr key={item.id}>
                  <td className="item-id">{item.id}</td>
                  <td className="item-name">{item.name}</td>
                  <td>
                    <span className={`type-badge type-${item.type.toLowerCase()}`}>
                      {item.type}
                    </span>
                  </td>
                  <td className="description">{item.description}</td>
                  <td className="amount">${item.price.toLocaleString('en-US', { minimumFractionDigits: 2 })}</td>
                  <td>{item.qty || '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {toast && <div className="toast">{toast}</div>}
    </div>
  );
};

export default App;
