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 mockPLData = [
  { category: 'Revenue', subcategory: 'Product Sales', amount: 125000.00 },
  { category: 'Revenue', subcategory: 'Service Revenue', amount: 85000.00 },
  { category: 'Cost of Goods Sold', subcategory: 'Product Costs', amount: 45000.00 },
  { category: 'Cost of Goods Sold', subcategory: 'Direct Labor', amount: 32000.00 },
  { category: 'Expenses', subcategory: 'Rent', amount: 12000.00 },
  { category: 'Expenses', subcategory: 'Salaries', amount: 48000.00 },
  { category: 'Expenses', subcategory: 'Marketing', amount: 18500.00 },
  { category: 'Expenses', subcategory: 'Utilities', amount: 4500.00 },
];

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

  const stats = useMemo(() => {
    const totalRevenue = mockPLData.filter(d => d.category === 'Revenue').reduce((s, d) => s + d.amount, 0);
    const totalCOGS = mockPLData.filter(d => d.category === 'Cost of Goods Sold').reduce((s, d) => s + d.amount, 0);
    const grossProfit = totalRevenue - totalCOGS;
    const totalExpenses = mockPLData.filter(d => d.category === 'Expenses').reduce((s, d) => s + d.amount, 0);
    const netIncome = grossProfit - totalExpenses;
    return { totalRevenue, totalCOGS, grossProfit, totalExpenses, netIncome };
  }, []);

  const handleDateChange = (range: string) => {
    startTransition(() => {
      setDateRange(range);
      showToast(`Date Range: ${range.toUpperCase()}`);
    });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Profit & Loss</h1>
        <p>Income statement with date range selection</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card stat-success">
          <div className="stat-label">Total Revenue</div>
          <div className="stat-value">${stats.totalRevenue.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-label">Gross Profit</div>
          <div className="stat-value">${stats.grossProfit.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card stat-danger">
          <div className="stat-label">Total Expenses</div>
          <div className="stat-value">${stats.totalExpenses.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Net Income</div>
          <div className="stat-value" style={{ color: stats.netIncome > 0 ? 'var(--success)' : 'var(--danger)' }}>
            ${stats.netIncome.toLocaleString('en-US', { minimumFractionDigits: 2 })}
          </div>
        </div>
      </div>

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

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

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

export default App;
