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 mockAccounts = [
  { id: 'ACC001', name: 'Cash - Operating', type: 'Bank', balance: 45000.00, accountNumber: '1000' },
  { id: 'ACC002', name: 'Accounts Receivable', type: 'Accounts Receivable', balance: 28500.00, accountNumber: '1200' },
  { id: 'ACC003', name: 'Inventory Asset', type: 'Other Current Assets', balance: 15000.00, accountNumber: '1300' },
  { id: 'ACC004', name: 'Office Equipment', type: 'Fixed Assets', balance: 12000.00, accountNumber: '1500' },
  { id: 'ACC005', name: 'Accounts Payable', type: 'Accounts Payable', balance: -18500.00, accountNumber: '2000' },
  { id: 'ACC006', name: 'Revenue - Services', type: 'Income', balance: -95000.00, accountNumber: '4000' },
  { id: 'ACC007', name: 'Cost of Goods Sold', type: 'Cost of Goods Sold', balance: 32000.00, accountNumber: '5000' },
  { id: 'ACC008', name: 'Rent Expense', type: 'Expenses', balance: 12000.00, accountNumber: '6000' },
];

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 filteredAccounts = useMemo(() => {
    return mockAccounts.filter((acc) => {
      const matchesSearch = acc.name.toLowerCase().includes(debouncedSearch.toLowerCase()) || acc.id.includes(debouncedSearch) || acc.accountNumber.includes(debouncedSearch);
      const matchesFilter = filterType === 'all' || acc.type === filterType;
      return matchesSearch && matchesFilter;
    });
  }, [debouncedSearch, filterType]);

  const stats = useMemo(() => {
    const assets = mockAccounts.filter(a => ['Bank', 'Accounts Receivable', 'Other Current Assets', 'Fixed Assets'].includes(a.type)).reduce((s, a) => s + a.balance, 0);
    const liabilities = Math.abs(mockAccounts.filter(a => a.type === 'Accounts Payable').reduce((s, a) => s + a.balance, 0));
    const income = Math.abs(mockAccounts.filter(a => a.type === 'Income').reduce((s, a) => s + a.balance, 0));
    const expenses = mockAccounts.filter(a => ['Expenses', 'Cost of Goods Sold'].includes(a.type)).reduce((s, a) => s + a.balance, 0);
    return { assets, liabilities, income, expenses };
  }, []);

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

  const types = ['all', ...Array.from(new Set(mockAccounts.map(a => a.type)))];

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Chart of Accounts</h1>
        <p>Account hierarchy, types, and balances</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card stat-success">
          <div className="stat-label">Total Assets</div>
          <div className="stat-value">${stats.assets.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card stat-danger">
          <div className="stat-label">Total Liabilities</div>
          <div className="stat-value">${stats.liabilities.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Income</div>
          <div className="stat-value">${stats.income.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-label">Total Expenses</div>
          <div className="stat-value">${stats.expenses.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
      </div>

      <div className="controls">
        <input type="text" className="search-input" placeholder="Search by name, ID, or account number..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} />
        <div className="filter-buttons">
          {types.slice(0, 4).map((type) => (
            <button key={type} className={`filter-btn ${filterType === type ? 'active' : ''}`} onClick={() => handleFilterChange(type)}>
              {type === 'all' ? 'All' : type}
            </button>
          ))}
        </div>
      </div>

      {filteredAccounts.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">🏦</div>
          <h3>No accounts found</h3>
          <p>Try adjusting your search or filters</p>
        </div>
      ) : (
        <div className={`data-grid ${isPending ? 'loading' : ''}`}>
          <table>
            <thead>
              <tr>
                <th>Account #</th>
                <th>Account Name</th>
                <th>Type</th>
                <th>Balance</th>
              </tr>
            </thead>
            <tbody>
              {filteredAccounts.map((account) => (
                <tr key={account.id}>
                  <td style={{ fontFamily: 'monospace', color: 'var(--accent-primary)', fontWeight: 600 }}>{account.accountNumber}</td>
                  <td style={{ fontWeight: 500 }}>{account.name}</td>
                  <td>{account.type}</td>
                  <td className="amount" style={{ color: account.balance < 0 ? 'var(--success)' : 'var(--text-primary)' }}>
                    ${Math.abs(account.balance).toLocaleString('en-US', { minimumFractionDigits: 2 })}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

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

export default App;
