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 mockExpenses = [
  { id: 'E001', date: '2024-01-15', vendor: 'Office Supplies Co', category: 'Supplies', amount: 450.00, type: 'Purchase' },
  { id: 'PO001', date: '2024-01-18', vendor: 'Tech Hardware Inc', category: 'Equipment', amount: 12000.00, type: 'Purchase Order' },
  { id: 'E002', date: '2024-01-20', vendor: 'Marketing Agency', category: 'Marketing', amount: 5500.00, type: 'Purchase' },
  { id: 'E003', date: '2024-01-22', vendor: 'Cloud Services LLC', category: 'Software', amount: 899.00, type: 'Purchase' },
  { id: 'PO002', date: '2024-01-25', vendor: 'Furniture Co', category: 'Furniture', amount: 3500.00, type: 'Purchase Order' },
  { id: 'E004', date: '2024-01-28', vendor: 'Utilities Provider', category: 'Utilities', amount: 450.00, type: 'Purchase' },
];

type Expense = typeof mockExpenses[0];

const App: React.FC = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [filterType, setFilterType] = useState<string>('all');
  const [isPending, startTransition] = useTransition();
  const { toast, showToast } = useToast();

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredExpenses = useMemo(() => {
    return mockExpenses.filter((expense) => {
      const matchesSearch =
        expense.vendor.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        expense.category.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        expense.id.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesFilter = filterType === 'all' || expense.type === filterType;
      return matchesSearch && matchesFilter;
    });
  }, [debouncedSearch, filterType]);

  const stats = useMemo(() => {
    const totalSpending = mockExpenses.reduce((sum, e) => sum + e.amount, 0);
    const purchases = mockExpenses.filter(e => e.type === 'Purchase').reduce((sum, e) => sum + e.amount, 0);
    const pos = mockExpenses.filter(e => e.type === 'Purchase Order').reduce((sum, e) => sum + e.amount, 0);
    const count = mockExpenses.length;
    return { totalSpending, purchases, pos, count };
  }, []);

  const handleFilterChange = (type: string) => {
    startTransition(() => {
      setFilterType(type);
      showToast(`Filter: ${type === 'all' ? 'All' : type}`);
    });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Expense Tracker</h1>
        <p>Purchases, purchase orders, and spending overview</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card stat-danger">
          <div className="stat-label">Total Spending</div>
          <div className="stat-value">${stats.totalSpending.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Purchases</div>
          <div className="stat-value">${stats.purchases.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Purchase Orders</div>
          <div className="stat-value">${stats.pos.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Transactions</div>
          <div className="stat-value">{stats.count}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          className="search-input"
          placeholder="Search by vendor, category, or ID..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        <div className="filter-buttons">
          {['all', 'Purchase', 'Purchase Order'].map((type) => (
            <button
              key={type}
              className={`filter-btn ${filterType === type ? 'active' : ''}`}
              onClick={() => handleFilterChange(type)}
            >
              {type === 'all' ? 'All' : type}
            </button>
          ))}
        </div>
      </div>

      {filteredExpenses.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">💰</div>
          <h3>No expenses found</h3>
          <p>Try adjusting your search or filters</p>
        </div>
      ) : (
        <div className={`data-grid ${isPending ? 'loading' : ''}`}>
          <table>
            <thead>
              <tr>
                <th>ID</th>
                <th>Date</th>
                <th>Vendor</th>
                <th>Category</th>
                <th>Type</th>
                <th>Amount</th>
              </tr>
            </thead>
            <tbody>
              {filteredExpenses.map((expense) => (
                <tr key={expense.id}>
                  <td className="expense-id">{expense.id}</td>
                  <td>{expense.date}</td>
                  <td className="vendor-name">{expense.vendor}</td>
                  <td>{expense.category}</td>
                  <td>
                    <span className={`type-badge type-${expense.type.toLowerCase().replace(' ', '-')}`}>
                      {expense.type}
                    </span>
                  </td>
                  <td className="amount">${expense.amount.toLocaleString('en-US', { minimumFractionDigits: 2 })}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

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

export default App;
