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 mockPayments = [
  { id: 'P001', customer: 'Acme Corp', amount: 5250.00, date: '2024-01-15', method: 'Credit Card', type: 'payment' },
  { id: 'P002', customer: 'Tech Solutions Inc', amount: 7500.00, date: '2024-01-18', method: 'ACH', type: 'payment' },
  { id: 'CM001', customer: 'Global Enterprises', amount: 1250.00, date: '2024-01-20', method: 'N/A', type: 'credit-memo' },
  { id: 'P003', customer: 'Startup LLC', amount: 3200.00, date: '2024-01-22', method: 'Check', type: 'payment' },
  { id: 'P004', customer: 'Enterprise Co', amount: 15000.00, date: '2024-01-25', method: 'Wire Transfer', type: 'payment' },
  { id: 'CM002', customer: 'Small Biz Inc', amount: 500.00, date: '2024-01-28', method: 'N/A', type: 'credit-memo' },
];

type Payment = typeof mockPayments[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 filteredPayments = useMemo(() => {
    return mockPayments.filter((payment) => {
      const matchesSearch =
        payment.customer.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        payment.id.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        payment.method.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesFilter = filterType === 'all' || payment.type === filterType;
      return matchesSearch && matchesFilter;
    });
  }, [debouncedSearch, filterType]);

  const stats = useMemo(() => {
    const totalPayments = mockPayments.filter(p => p.type === 'payment').reduce((sum, p) => sum + p.amount, 0);
    const totalCredits = mockPayments.filter(p => p.type === 'credit-memo').reduce((sum, p) => sum + p.amount, 0);
    const paymentCount = mockPayments.filter(p => p.type === 'payment').length;
    const creditCount = mockPayments.filter(p => p.type === 'credit-memo').length;
    return { totalPayments, totalCredits, paymentCount, creditCount };
  }, []);

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

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Payment Tracker</h1>
        <p>Received payments and credit memos</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card stat-success">
          <div className="stat-label">Total Payments</div>
          <div className="stat-value">${stats.totalPayments.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
          <div className="stat-count">{stats.paymentCount} transactions</div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-label">Credit Memos</div>
          <div className="stat-value">${stats.totalCredits.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
          <div className="stat-count">{stats.creditCount} memos</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Net Received</div>
          <div className="stat-value">${(stats.totalPayments - stats.totalCredits).toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Transactions</div>
          <div className="stat-value">{mockPayments.length}</div>
        </div>
      </div>

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

      {filteredPayments.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">💳</div>
          <h3>No transactions 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>Customer</th>
                <th>Type</th>
                <th>Method</th>
                <th>Amount</th>
              </tr>
            </thead>
            <tbody>
              {filteredPayments.map((payment) => (
                <tr key={payment.id}>
                  <td className="payment-id">{payment.id}</td>
                  <td>{payment.date}</td>
                  <td className="customer-name">{payment.customer}</td>
                  <td>
                    <span className={`type-badge type-${payment.type}`}>
                      {payment.type === 'payment' ? 'Payment' : 'Credit Memo'}
                    </span>
                  </td>
                  <td>{payment.method}</td>
                  <td className="amount">${payment.amount.toLocaleString('en-US', { minimumFractionDigits: 2 })}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

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

export default App;
