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 mockJournalEntries = [
  { id: 'JE001', date: '2024-01-15', account: 'Cash', debit: 5000.00, credit: 0, memo: 'Owner contribution' },
  { id: 'JE001', date: '2024-01-15', account: 'Owner\'s Equity', debit: 0, credit: 5000.00, memo: 'Owner contribution' },
  { id: 'JE002', date: '2024-01-20', account: 'Rent Expense', debit: 2000.00, credit: 0, memo: 'Monthly rent adjustment' },
  { id: 'JE002', date: '2024-01-20', account: 'Prepaid Rent', debit: 0, credit: 2000.00, memo: 'Monthly rent adjustment' },
  { id: 'JE003', date: '2024-01-25', account: 'Depreciation Expense', debit: 500.00, credit: 0, memo: 'Monthly depreciation' },
  { id: 'JE003', date: '2024-01-25', account: 'Accumulated Depreciation', debit: 0, credit: 500.00, memo: 'Monthly depreciation' },
];

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

  const filteredEntries = useMemo(() => {
    return mockJournalEntries.filter((entry) => {
      return entry.account.toLowerCase().includes(debouncedSearch.toLowerCase()) || entry.id.includes(debouncedSearch) || entry.memo.toLowerCase().includes(debouncedSearch.toLowerCase());
    });
  }, [debouncedSearch]);

  const stats = useMemo(() => {
    const uniqueEntries = new Set(mockJournalEntries.map(e => e.id)).size;
    const totalDebits = mockJournalEntries.reduce((s, e) => s + e.debit, 0);
    const totalCredits = mockJournalEntries.reduce((s, e) => s + e.credit, 0);
    const difference = Math.abs(totalDebits - totalCredits);
    return { uniqueEntries, totalDebits, totalCredits, difference };
  }, []);

  const handleSearch = (query: string) => {
    startTransition(() => {
      setSearchQuery(query);
      if (query) showToast(`Searching: ${query}`);
    });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Journal Entries</h1>
        <p>Journal entry viewer and adjustments</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Journal Entries</div>
          <div className="stat-value">{stats.uniqueEntries}</div>
        </div>
        <div className="stat-card stat-success">
          <div className="stat-label">Total Debits</div>
          <div className="stat-value">${stats.totalDebits.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-label">Total Credits</div>
          <div className="stat-value">${stats.totalCredits.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Balance Check</div>
          <div className="stat-value" style={{ color: stats.difference === 0 ? 'var(--success)' : 'var(--danger)' }}>
            {stats.difference === 0 ? '✓ Balanced' : `${stats.difference.toFixed(2)} Off`}
          </div>
        </div>
      </div>

      <div className="controls">
        <input type="text" className="search-input" placeholder="Search by account, ID, or memo..." value={searchQuery} onChange={(e) => handleSearch(e.target.value)} />
      </div>

      {filteredEntries.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">📖</div>
          <h3>No journal entries found</h3>
          <p>Try adjusting your search</p>
        </div>
      ) : (
        <div className={`data-grid ${isPending ? 'loading' : ''}`}>
          <table>
            <thead>
              <tr>
                <th>Entry ID</th>
                <th>Date</th>
                <th>Account</th>
                <th>Memo</th>
                <th>Debit</th>
                <th>Credit</th>
              </tr>
            </thead>
            <tbody>
              {filteredEntries.map((entry, idx) => (
                <tr key={idx}>
                  <td style={{ fontFamily: 'monospace', color: 'var(--accent-primary)', fontWeight: 600 }}>{entry.id}</td>
                  <td>{entry.date}</td>
                  <td style={{ fontWeight: 500 }}>{entry.account}</td>
                  <td style={{ fontSize: '0.875rem', color: 'var(--text-muted)' }}>{entry.memo}</td>
                  <td className="amount">{entry.debit > 0 ? `$${entry.debit.toFixed(2)}` : '—'}</td>
                  <td className="amount">{entry.credit > 0 ? `$${entry.credit.toFixed(2)}` : '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

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

export default App;
