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 mockSalesData = [
  { customer: 'Acme Corp', revenue: 45000.00, transactions: 12, avgSale: 3750.00 },
  { customer: 'Tech Solutions Inc', revenue: 38500.00, transactions: 9, avgSale: 4277.78 },
  { customer: 'Global Enterprises', revenue: 32000.00, transactions: 8, avgSale: 4000.00 },
  { customer: 'Startup LLC', revenue: 28000.00, transactions: 14, avgSale: 2000.00 },
  { customer: 'Enterprise Co', revenue: 25000.00, transactions: 5, avgSale: 5000.00 },
  { customer: 'Small Biz Inc', revenue: 12500.00, transactions: 10, avgSale: 1250.00 },
];

const App: React.FC = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState<string>('revenue');
  const [isPending, startTransition] = useTransition();
  const { toast, showToast } = useToast();
  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredData = useMemo(() => {
    let data = mockSalesData.filter((item) => item.customer.toLowerCase().includes(debouncedSearch.toLowerCase()));
    if (sortBy === 'revenue') data.sort((a, b) => b.revenue - a.revenue);
    else if (sortBy === 'transactions') data.sort((a, b) => b.transactions - a.transactions);
    else if (sortBy === 'avgSale') data.sort((a, b) => b.avgSale - a.avgSale);
    return data;
  }, [debouncedSearch, sortBy]);

  const stats = useMemo(() => {
    const totalRevenue = mockSalesData.reduce((s, d) => s + d.revenue, 0);
    const totalTransactions = mockSalesData.reduce((s, d) => s + d.transactions, 0);
    const topCustomer = mockSalesData.reduce((max, d) => d.revenue > max.revenue ? d : max, mockSalesData[0]);
    const avgTransaction = totalRevenue / totalTransactions;
    return { totalRevenue, totalTransactions, topCustomer: topCustomer.customer, avgTransaction };
  }, []);

  const handleSortChange = (sort: string) => {
    startTransition(() => {
      setSortBy(sort);
      showToast(`Sort: ${sort === 'revenue' ? 'Revenue' : sort === 'transactions' ? 'Transactions' : 'Avg Sale'}`);
    });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Sales Dashboard</h1>
        <p>Revenue metrics, top customers, and trends</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card stat-success">
          <div className="stat-label">Total Revenue</div>
          <div className="stat-value">${stats.totalRevenue.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Transactions</div>
          <div className="stat-value">{stats.totalTransactions}</div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-label">Top Customer</div>
          <div className="stat-value" style={{ fontSize: '1.5rem' }}>{stats.topCustomer}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Avg Transaction</div>
          <div className="stat-value">${stats.avgTransaction.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
      </div>

      <div className="controls">
        <input type="text" className="search-input" placeholder="Search customers..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} />
        <div className="filter-buttons">
          {['revenue', 'transactions', 'avgSale'].map((sort) => (
            <button key={sort} className={`filter-btn ${sortBy === sort ? 'active' : ''}`} onClick={() => handleSortChange(sort)}>
              {sort === 'revenue' ? 'Revenue' : sort === 'transactions' ? 'Transactions' : 'Avg Sale'}
            </button>
          ))}
        </div>
      </div>

      {filteredData.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">📊</div>
          <h3>No sales data found</h3>
          <p>Try adjusting your search</p>
        </div>
      ) : (
        <div className={`data-grid ${isPending ? 'loading' : ''}`}>
          <table>
            <thead>
              <tr>
                <th>Customer</th>
                <th>Revenue</th>
                <th>Transactions</th>
                <th>Avg Sale</th>
              </tr>
            </thead>
            <tbody>
              {filteredData.map((item, idx) => (
                <tr key={idx}>
                  <td style={{ fontWeight: 500 }}>{item.customer}</td>
                  <td className="amount">${item.revenue.toLocaleString('en-US', { minimumFractionDigits: 2 })}</td>
                  <td>{item.transactions}</td>
                  <td className="amount">${item.avgSale.toLocaleString('en-US', { minimumFractionDigits: 2 })}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

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

export default App;
