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

const mockData = [
  {
    "id": "v1",
    "product": "T-Shirt",
    "variant": "Small / Red",
    "sku": "TS-S-R",
    "stock": 45,
    "price": "$24.99",
    "status": "active"
  },
  {
    "id": "v2",
    "product": "T-Shirt",
    "variant": "Medium / Blue",
    "sku": "TS-M-B",
    "stock": 8,
    "price": "$24.99",
    "status": "active"
  },
  {
    "id": "v3",
    "product": "Shoes",
    "variant": "Size 10 / Black",
    "sku": "SH-10-BK",
    "stock": 0,
    "price": "$89.99",
    "status": "draft"
  },
  {
    "id": "v4",
    "product": "Hat",
    "variant": "One Size / Green",
    "sku": "HT-OS-G",
    "stock": 123,
    "price": "$19.99",
    "status": "active"
  }
];

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 filteredData = useMemo(() => {
    return mockData.filter((item: any) => {
      const searchField = Object.values(item).join(' ').toLowerCase();
      const matchesSearch = searchField.includes(debouncedSearch.toLowerCase());
      const matchesStatus = statusFilter === 'all' || item.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [debouncedSearch, statusFilter]);

  const stats = useMemo(() => ({
    total: mockData.length,
    active: mockData.filter((i: any) => i.status === 'active').length,
    value1: Math.floor(Math.random() * 1000),
    value2: Math.floor(Math.random() * 100),
  }), []);

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

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Variant Manager</h1>
        <p>Manage product variants</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">In Stock</div>
          <div className="stat-value">{stats.active}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Low Stock</div>
          <div className="stat-value">{stats.value1}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Out</div>
          <div className="stat-value">{stats.value2}</div>
        </div>
      </div>

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

      {filteredData.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">🎯</div>
          <h3>No data found</h3>
          <p>Try adjusting your search or filters</p>
        </div>
      ) : (
        <div className="data-grid" style={{ opacity: isPending ? 0.6 : 1 }}>
          {filteredData.map((item: any) => (
            <div key={item.id} className="data-card">
              <h3>{Object.values(item)[1] as string}</h3>
              <p>{Object.values(item)[2] as string}</p>
              <div style={{ marginTop: '1rem' }}>
                <span className={`status-badge status-${item.status}`}>
                  {item.status}
                </span>
              </div>
            </div>
          ))}
        </div>
      )}

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