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 mockBankTransactions = [
  { id: 'BT001', date: '2024-01-15', description: 'Customer Payment - Acme Corp', type: 'Deposit', amount: 5000.00, reconciled: true },
  { id: 'BT002', date: '2024-01-16', description: 'Vendor Payment - Office Supplies', type: 'Check', amount: -450.00, reconciled: true },
  { id: 'BT003', date: '2024-01-18', description: 'ACH Transfer - Payroll', type: 'Transfer', amount: -12000.00, reconciled: false },
  { id: 'BT004', date: '2024-01-20', description: 'Customer Payment - Tech Solutions', type: 'Deposit', amount: 7500.00, reconciled: true },
  { id: 'BT005', date: '2024-01-22', description: 'Bank Fee', type: 'Fee', amount: -25.00, reconciled: false },
  { id: 'BT006', date: '2024-01-25', description: 'Customer Payment - Global Ent', type: 'Deposit', amount: 8750.00, reconciled: false },
];

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

  const filteredTransactions = useMemo(() => {
    return mockBankTransactions.filter((txn) => {
      const matchesSearch = txn.description.toLowerCase().includes(debouncedSearch.toLowerCase()) || txn.id.includes(debouncedSearch);
      const matchesFilter = filterStatus === 'all' || (filterStatus === 'reconciled' && txn.reconciled) || (filterStatus === 'unreconciled' && !txn.reconciled);
      return matchesSearch && matchesFilter;
    });
  }, [debouncedSearch, filterStatus]);

  const stats = useMemo(() => {
    const totalDeposits = mockBankTransactions.filter(t => t.amount > 0).reduce((s, t) => s + t.amount, 0);
    const totalWithdrawals = Math.abs(mockBankTransactions.filter(t => t.amount < 0).reduce((s, t) => s + t.amount, 0));
    const reconciled = mockBankTransactions.filter(t => t.reconciled).length;
    const unreconciled = mockBankTransactions.filter(t => !t.reconciled).length;
    const balance = totalDeposits - totalWithdrawals;
    return { totalDeposits, totalWithdrawals, reconciled, unreconciled, balance };
  }, []);

  const handleFilterChange = (status: string) => {
    startTransition(() => {
      setFilterStatus(status);
      showToast(`Filter: ${status === 'all' ? 'All Transactions' : status === 'reconciled' ? 'Reconciled' : 'Unreconciled'}`);
    });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Bank Reconciliation</h1>
        <p>Deposits, transfers, and bank feeds</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card stat-success">
          <div className="stat-label">Total Deposits</div>
          <div className="stat-value">${stats.totalDeposits.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card stat-danger">
          <div className="stat-label">Total Withdrawals</div>
          <div className="stat-value">${stats.totalWithdrawals.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Reconciled</div>
          <div className="stat-value">{stats.reconciled}</div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-label">Unreconciled</div>
          <div className="stat-value">{stats.unreconciled}</div>
        </div>
      </div>

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

      {filteredTransactions.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>Description</th>
                <th>Type</th>
                <th>Amount</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {filteredTransactions.map((txn) => (
                <tr key={txn.id}>
                  <td style={{ fontFamily: 'monospace', color: 'var(--accent-primary)', fontWeight: 600 }}>{txn.id}</td>
                  <td>{txn.date}</td>
                  <td style={{ fontWeight: 500 }}>{txn.description}</td>
                  <td>{txn.type}</td>
                  <td className="amount" style={{ color: txn.amount > 0 ? 'var(--success)' : 'var(--danger)' }}>
                    ${Math.abs(txn.amount).toLocaleString('en-US', { minimumFractionDigits: 2 })}
                  </td>
                  <td>
                    <span style={{ display: 'inline-block', padding: '0.375rem 0.75rem', borderRadius: '9999px', fontSize: '0.75rem', fontWeight: 600, background: txn.reconciled ? 'rgba(16, 185, 129, 0.1)' : 'rgba(245, 158, 11, 0.1)', color: txn.reconciled ? 'var(--success)' : 'var(--warning)' }}>
                      {txn.reconciled ? 'Reconciled' : 'Pending'}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

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

export default App;
