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 mockBalanceSheet = [
  { section: 'Assets', category: 'Current Assets', item: 'Cash', amount: 45000.00 },
  { section: 'Assets', category: 'Current Assets', item: 'Accounts Receivable', amount: 28500.00 },
  { section: 'Assets', category: 'Current Assets', item: 'Inventory', amount: 15000.00 },
  { section: 'Assets', category: 'Fixed Assets', item: 'Equipment', amount: 12000.00 },
  { section: 'Liabilities', category: 'Current Liabilities', item: 'Accounts Payable', amount: 18500.00 },
  { section: 'Liabilities', category: 'Long-term Liabilities', item: 'Loan Payable', amount: 25000.00 },
  { section: 'Equity', category: 'Equity', item: 'Owner\'s Equity', amount: 50000.00 },
  { section: 'Equity', category: 'Equity', item: 'Retained Earnings', amount: 7000.00 },
];

const App: React.FC = () => {
  const [dateFilter, setDateFilter] = useState('current');
  const [isPending, startTransition] = useTransition();
  const { toast, showToast } = useToast();

  const stats = useMemo(() => {
    const totalAssets = mockBalanceSheet.filter(d => d.section === 'Assets').reduce((s, d) => s + d.amount, 0);
    const totalLiabilities = mockBalanceSheet.filter(d => d.section === 'Liabilities').reduce((s, d) => s + d.amount, 0);
    const totalEquity = mockBalanceSheet.filter(d => d.section === 'Equity').reduce((s, d) => s + d.amount, 0);
    const liabilitiesEquity = totalLiabilities + totalEquity;
    return { totalAssets, totalLiabilities, totalEquity, liabilitiesEquity };
  }, []);

  const handleDateChange = (filter: string) => {
    startTransition(() => {
      setDateFilter(filter);
      showToast(`As of: ${filter === 'current' ? 'Current Date' : filter}`);
    });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Balance Sheet</h1>
        <p>Financial position and account 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.totalAssets.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.totalLiabilities.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-label">Total Equity</div>
          <div className="stat-value">${stats.totalEquity.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Liabilities + Equity</div>
          <div className="stat-value">${stats.liabilitiesEquity.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
      </div>

      <div className="controls">
        <div className="filter-buttons">
          {['current', '2024-01-01', '2023-12-31'].map((filter) => (
            <button key={filter} className={`filter-btn ${dateFilter === filter ? 'active' : ''}`} onClick={() => handleDateChange(filter)}>
              {filter === 'current' ? 'Current' : filter}
            </button>
          ))}
        </div>
      </div>

      <div className={`data-grid ${isPending ? 'loading' : ''}`}>
        <table>
          <thead>
            <tr>
              <th>Section</th>
              <th>Category</th>
              <th>Item</th>
              <th>Amount</th>
            </tr>
          </thead>
          <tbody>
            {mockBalanceSheet.map((item, idx) => (
              <tr key={idx}>
                <td style={{ fontWeight: 600 }}>{item.section}</td>
                <td>{item.category}</td>
                <td>{item.item}</td>
                <td className="amount">${item.amount.toLocaleString('en-US', { minimumFractionDigits: 2 })}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

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

export default App;
