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": "sd1",
    "date": "2024-02-13",
    "sales": "$1,234",
    "orders": 23,
    "avgOrder": "$54",
    "status": "active"
  },
  {
    "id": "sd2",
    "date": "2024-02-12",
    "sales": "$2,456",
    "orders": 34,
    "avgOrder": "$72",
    "status": "active"
  },
  {
    "id": "sd3",
    "date": "2024-02-11",
    "sales": "$1,890",
    "orders": 28,
    "avgOrder": "$68",
    "status": "active"
  },
  {
    "id": "sd4",
    "date": "2024-02-10",
    "sales": "$3,123",
    "orders": 45,
    "avgOrder": "$69",
    "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>Sales Dashboard</h1>
        <p>Track revenue and performance</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Today</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">This Week</div>
          <div className="stat-value">{stats.active}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">This Month</div>
          <div className="stat-value">{stats.value1}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Growth</div>
          <div className="stat-value">{stats.value2}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          placeholder="Search transactions..."
          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>
  );
}