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 mockCashFlow = [
  { category: 'Operating Activities', item: 'Cash from Customers', amount: 210000.00 },
  { category: 'Operating Activities', item: 'Cash to Suppliers', amount: -77000.00 },
  { category: 'Operating Activities', item: 'Cash for Operating Expenses', amount: -83000.00 },
  { category: 'Investing Activities', item: 'Purchase of Equipment', amount: -12000.00 },
  { category: 'Financing Activities', item: 'Loan Proceeds', amount: 25000.00 },
  { category: 'Financing Activities', item: 'Owner Distributions', amount: -15000.00 },
];

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

  const stats = useMemo(() => {
    const operating = mockCashFlow.filter(d => d.category === 'Operating Activities').reduce((s, d) => s + d.amount, 0);
    const investing = mockCashFlow.filter(d => d.category === 'Investing Activities').reduce((s, d) => s + d.amount, 0);
    const financing = mockCashFlow.filter(d => d.category === 'Financing Activities').reduce((s, d) => s + d.amount, 0);
    const netChange = operating + investing + financing;
    return { operating, investing, financing, netChange };
  }, []);

  const handlePeriodChange = (period: string) => {
    startTransition(() => {
      setPeriodFilter(period);
      showToast(`Period: ${period.toUpperCase()}`);
    });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Cash Flow Statement</h1>
        <p>Cash inflows and outflows by activity</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card stat-success">
          <div className="stat-label">Operating Activities</div>
          <div className="stat-value" style={{ color: stats.operating > 0 ? 'var(--success)' : 'var(--danger)' }}>
            ${stats.operating.toLocaleString('en-US', { minimumFractionDigits: 2 })}
          </div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-label">Investing Activities</div>
          <div className="stat-value" style={{ color: stats.investing > 0 ? 'var(--success)' : 'var(--danger)' }}>
            ${stats.investing.toLocaleString('en-US', { minimumFractionDigits: 2 })}
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Financing Activities</div>
          <div className="stat-value" style={{ color: stats.financing > 0 ? 'var(--success)' : 'var(--danger)' }}>
            ${stats.financing.toLocaleString('en-US', { minimumFractionDigits: 2 })}
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Net Cash Change</div>
          <div className="stat-value" style={{ color: stats.netChange > 0 ? 'var(--success)' : 'var(--danger)' }}>
            ${stats.netChange.toLocaleString('en-US', { minimumFractionDigits: 2 })}
          </div>
        </div>
      </div>

      <div className="controls">
        <div className="filter-buttons">
          {['mtd', 'qtd', 'ytd'].map((period) => (
            <button key={period} className={`filter-btn ${periodFilter === period ? 'active' : ''}`} onClick={() => handlePeriodChange(period)}>
              {period.toUpperCase()}
            </button>
          ))}
        </div>
      </div>

      <div className={`data-grid ${isPending ? 'loading' : ''}`}>
        <table>
          <thead>
            <tr>
              <th>Category</th>
              <th>Item</th>
              <th>Amount</th>
            </tr>
          </thead>
          <tbody>
            {mockCashFlow.map((item, idx) => (
              <tr key={idx}>
                <td style={{ fontWeight: 600 }}>{item.category}</td>
                <td>{item.item}</td>
                <td className="amount" style={{ color: item.amount > 0 ? 'var(--success)' : 'var(--danger)' }}>
                  ${item.amount.toLocaleString('en-US', { minimumFractionDigits: 2 })}
                </td>
              </tr>
            ))}
            <tr style={{ borderTop: '2px solid var(--border-color)', fontWeight: 700 }}>
              <td colSpan={2}>NET CASH CHANGE</td>
              <td className="amount" style={{ color: stats.netChange > 0 ? 'var(--success)' : 'var(--danger)' }}>
                ${stats.netChange.toLocaleString('en-US', { minimumFractionDigits: 2 })}
              </td>
            </tr>
          </tbody>
        </table>
      </div>

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

export default App;
