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 Collection = {
  id: string;
  title: string;
  handle: string;
  products: number;
  status: 'active' | 'draft';
  type: 'manual' | 'automated';
  image: string;
};

const mockCollections: Collection[] = [
  { id: 'col1', title: 'Summer Collection', handle: 'summer-2024', products: 45, status: 'active', type: 'manual', image: '☀️' },
  { id: 'col2', title: 'Best Sellers', handle: 'best-sellers', products: 28, status: 'active', type: 'automated', image: '⭐' },
  { id: 'col3', title: 'New Arrivals', handle: 'new-arrivals', products: 32, status: 'active', type: 'automated', image: '🆕' },
  { id: 'col4', title: 'Sale Items', handle: 'sale', products: 67, status: 'active', type: 'manual', image: '🏷️' },
  { id: 'col5', title: 'Winter Collection', handle: 'winter-2024', products: 23, status: 'draft', type: 'manual', image: '❄️' },
  { id: 'col6', title: 'Accessories', handle: 'accessories', products: 54, status: 'active', type: 'manual', image: '👜' },
  { id: 'col7', title: 'Gift Ideas', handle: 'gifts', products: 41, status: 'active', type: 'manual', image: '🎁' },
  { id: 'col8', title: 'Trending Now', handle: 'trending', products: 19, status: 'active', type: 'automated', 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 filteredCollections = useMemo(() => {
    return mockCollections.filter(c => {
      const matchesSearch = c.title.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
                           c.handle.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesStatus = statusFilter === 'all' || c.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [debouncedSearch, statusFilter]);

  const stats = useMemo(() => ({
    total: mockCollections.length,
    active: mockCollections.filter(c => c.status === 'active').length,
    totalProducts: mockCollections.reduce((sum, c) => sum + c.products, 0),
    automated: mockCollections.filter(c => c.type === 'automated').length,
  }), []);

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

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Collection Manager</h1>
        <p>Organize products into collections</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Collections</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">Total Products</div>
          <div className="stat-value">{stats.totalProducts}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Automated</div>
          <div className="stat-value">{stats.automated}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          placeholder="Search collections..."
          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>

      {filteredCollections.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">📁</div>
          <h3>No collections found</h3>
          <p>Try adjusting your search or filters</p>
        </div>
      ) : (
        <div className="data-grid" style={{ opacity: isPending ? 0.6 : 1 }}>
          {filteredCollections.map(collection => (
            <div key={collection.id} className="data-card">
              <div className="collection-image">{collection.image}</div>
              <div className="data-card-content">
                <h3>{collection.title}</h3>
                <p className="collection-handle">/{collection.handle}</p>
                <div className="collection-meta">
                  <span>{collection.products} products</span>
                  <span className={`type-badge type-${collection.type}`}>
                    {collection.type}
                  </span>
                </div>
                <div className="collection-footer">
                  <span className={`status-badge status-${collection.status}`}>
                    {collection.status}
                  </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>
  );
}
