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 mockAgingData = [
  { customer: 'Acme Corp', current: 5000.00, days30: 2500.00, days60: 1000.00, days90: 500.00, over90: 0 },
  { customer: 'Tech Solutions Inc', current: 12500.00, days30: 0, days60: 0, days90: 0, over90: 0 },
  { customer: 'Global Enterprises', current: 0, days30: 3000.00, days60: 2500.00, days90: 1500.00, over90: 750.00 },
  { customer: 'Startup LLC', current: 3200.00, days30: 0, days60: 0, days90: 0, over90: 0 },
  { customer: 'Small Biz Inc', current: 0, days30: 850.00, days60: 1000.00, days90: 0, over90: 0 },
];

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

  const filteredData = useMemo(() => {
    return mockAgingData.filter((item) => item.customer.toLowerCase().includes(debouncedSearch.toLowerCase()));
  }, [debouncedSearch]);

  const stats = useMemo(() => {
    const current = mockAgingData.reduce((s, d) => s + d.current, 0);
    const days30 = mockAgingData.reduce((s, d) => s + d.days30, 0);
    const days60 = mockAgingData.reduce((s, d) => s + d.days60, 0);
    const days90Plus = mockAgingData.reduce((s, d) => s + d.days90 + d.over90, 0);
    const total = current + days30 + days60 + days90Plus;
    return { current, days30, days60, days90Plus, total };
  }, []);

  const handleReportChange = (type: string) => {
    startTransition(() => {
      setReportType(type);
      showToast(`Report: ${type === 'ar' ? 'Accounts Receivable' : 'Accounts Payable'} Aging`);
    });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Aging Reports</h1>
        <p>AR/AP aging summary and overdue amounts</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card stat-success">
          <div className="stat-label">Current</div>
          <div className="stat-value">${stats.current.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-label">1-30 Days</div>
          <div className="stat-value">${stats.days30.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card stat-danger">
          <div className="stat-label">31-60 Days</div>
          <div className="stat-value">${stats.days60.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card stat-danger">
          <div className="stat-label">90+ Days</div>
          <div className="stat-value">${stats.days90Plus.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
      </div>

      <div className="controls">
        <input type="text" className="search-input" placeholder="Search customers..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} />
        <div className="filter-buttons">
          {['ar', 'ap'].map((type) => (
            <button key={type} className={`filter-btn ${reportType === type ? 'active' : ''}`} onClick={() => handleReportChange(type)}>
              {type === 'ar' ? 'A/R Aging' : 'A/P Aging'}
            </button>
          ))}
        </div>
      </div>

      {filteredData.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">📅</div>
          <h3>No aging data found</h3>
          <p>Try adjusting your search</p>
        </div>
      ) : (
        <div className={`data-grid ${isPending ? 'loading' : ''}`}>
          <table>
            <thead>
              <tr>
                <th>Customer</th>
                <th>Current</th>
                <th>1-30 Days</th>
                <th>31-60 Days</th>
                <th>61-90 Days</th>
                <th>Over 90</th>
                <th>Total</th>
              </tr>
            </thead>
            <tbody>
              {filteredData.map((item, idx) => {
                const total = item.current + item.days30 + item.days60 + item.days90 + item.over90;
                return (
                  <tr key={idx}>
                    <td style={{ fontWeight: 500 }}>{item.customer}</td>
                    <td className="amount">${item.current.toFixed(2)}</td>
                    <td className="amount">${item.days30.toFixed(2)}</td>
                    <td className="amount">${item.days60.toFixed(2)}</td>
                    <td className="amount">${item.days90.toFixed(2)}</td>
                    <td className="amount">${item.over90.toFixed(2)}</td>
                    <td className="amount" style={{ fontWeight: 700 }}>${total.toFixed(2)}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

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

export default App;
