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 InventoryItem = {
  id: string;
  product: string;
  sku: string;
  location: string;
  available: number;
  committed: number;
  incoming: number;
  status: 'in-stock' | 'low' | 'out';
};

const mockInventory: InventoryItem[] = [
  { id: 'i1', product: 'Classic T-Shirt', sku: 'TS-001', location: 'Main Warehouse', available: 150, committed: 25, incoming: 100, status: 'in-stock' },
  { id: 'i2', product: 'Running Shoes', sku: 'RS-002', location: 'Main Warehouse', available: 8, committed: 12, incoming: 50, status: 'low' },
  { id: 'i3', product: 'Wireless Headphones', sku: 'WH-003', location: 'Store Front', available: 32, committed: 8, incoming: 0, status: 'in-stock' },
  { id: 'i4', product: 'Yoga Mat', sku: 'YM-004', location: 'Main Warehouse', available: 0, committed: 5, incoming: 75, status: 'out' },
  { id: 'i5', product: 'Coffee Mug Set', sku: 'CM-005', location: 'Store Front', available: 200, committed: 15, incoming: 0, status: 'in-stock' },
  { id: 'i6', product: 'Laptop Backpack', sku: 'LB-006', location: 'Main Warehouse', available: 5, committed: 3, incoming: 25, status: 'low' },
  { id: 'i7', product: 'Smart Watch', sku: 'SW-007', location: 'Store Front', available: 8, committed: 2, incoming: 20, status: 'low' },
  { id: 'i8', product: 'Desk Plant', sku: 'DP-008', location: 'Main Warehouse', available: 120, committed: 10, incoming: 0, status: 'in-stock' },
];

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

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredInventory = useMemo(() => {
    return mockInventory.filter(item => {
      const matchesSearch = item.product.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
                           item.sku.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesStatus = statusFilter === 'all' || item.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [debouncedSearch, statusFilter]);

  const stats = useMemo(() => ({
    totalItems: mockInventory.length,
    lowStock: mockInventory.filter(i => i.status === 'low').length,
    outOfStock: mockInventory.filter(i => i.status === 'out').length,
    totalValue: mockInventory.reduce((sum, i) => sum + i.available, 0),
  }), []);

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

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Inventory Tracker</h1>
        <p>Monitor stock levels across all locations</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Items</div>
          <div className="stat-value">{stats.totalItems}</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 className="stat-card">
          <div className="stat-label">Out of Stock</div>
          <div className="stat-value" style={{ color: stats.outOfStock > 0 ? '#ef4444' : 'inherit' }}>
            {stats.outOfStock}
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Units</div>
          <div className="stat-value">{stats.totalValue}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          placeholder="Search inventory..."
          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="in-stock">In Stock</option>
          <option value="low">Low Stock</option>
          <option value="out">Out of Stock</option>
        </select>
      </div>

      {filteredInventory.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">📦</div>
          <h3>No inventory found</h3>
          <p>Try adjusting your search or filters</p>
        </div>
      ) : (
        <div className="data-table" style={{ opacity: isPending ? 0.6 : 1 }}>
          <table>
            <thead>
              <tr>
                <th>Product</th>
                <th>SKU</th>
                <th>Location</th>
                <th>Available</th>
                <th>Committed</th>
                <th>Incoming</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {filteredInventory.map(item => (
                <tr key={item.id}>
                  <td className="product-name">{item.product}</td>
                  <td className="sku-code">{item.sku}</td>
                  <td>{item.location}</td>
                  <td className="inventory-count">{item.available}</td>
                  <td>{item.committed}</td>
                  <td className="incoming-count">{item.incoming > 0 ? `+${item.incoming}` : '-'}</td>
                  <td>
                    <span className={`status-badge status-${item.status}`}>
                      {item.status.replace('-', ' ')}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

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