import React, { useState, useMemo, useTransition, useEffect } from 'react';

const useDebounce = <T,>(value: T, delay: number): T => {
  const [debouncedValue, setDebouncedValue] = useState(value);
  useEffect(() => {
    const handler = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(handler);
  }, [value, delay]);
  return debouncedValue;
};

const useToast = () => {
  const [toasts, setToasts] = useState<Array<{ id: number; message: string; type: string }>>([]);
  const show = (message: string, type = 'info') => {
    const id = Date.now();
    setToasts((prev) => [...prev, { id, message, type }]);
    setTimeout(() => setToasts((prev) => prev.filter((t) => t.id !== id)), 3000);
  };
  return { toasts, show };
};

const mockRevenueData = [
  { period: 'Jan 2024', revenue: 125000, transactions: 450, avgValue: 278 },
  { period: 'Feb 2024', revenue: 142000, transactions: 520, avgValue: 273 },
  { period: 'Mar 2024', revenue: 138000, transactions: 495, avgValue: 279 },
  { period: 'Apr 2024', revenue: 165000, transactions: 580, avgValue: 284 },
  { period: 'May 2024', revenue: 178000, transactions: 620, avgValue: 287 },
  { period: 'Jun 2024', revenue: 195000, transactions: 670, avgValue: 291 },
];

const App = () => {
  const [timeRange, setTimeRange] = useState('6m');
  const [isPending, startTransition] = useTransition();
  const { toasts, show } = useToast();

  const filteredData = useMemo(() => {
    const ranges: Record<string, number> = { '3m': 3, '6m': 6, '12m': 12 };
    const limit = ranges[timeRange] || 6;
    return mockRevenueData.slice(-limit);
  }, [timeRange]);

  const stats = useMemo(() => {
    const totalRevenue = filteredData.reduce((sum, d) => sum + d.revenue, 0);
    const avgRevenue = totalRevenue / filteredData.length;
    const growth = filteredData.length > 1
      ? ((filteredData[filteredData.length - 1].revenue - filteredData[0].revenue) / filteredData[0].revenue) * 100
      : 0;
    const totalTransactions = filteredData.reduce((sum, d) => sum + d.transactions, 0);
    return { totalRevenue, avgRevenue, growth, totalTransactions };
  }, [filteredData]);

  const handleTimeRangeChange = (range: string) => {
    startTransition(() => {
      setTimeRange(range);
      show(`Showing ${range} data`, 'info');
    });
  };

  const formatAmount = (amount: number) => {
    return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount / 100);
  };

  const formatPercent = (value: number) => {
    return `${value >= 0 ? '+' : ''}${value.toFixed(1)}%`;
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Revenue Analytics</h1>
        <p className="subtitle">Revenue over time, growth metrics, and trends</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Revenue</div>
          <div className="stat-value">{formatAmount(stats.totalRevenue)}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Average Revenue</div>
          <div className="stat-value stat-success">{formatAmount(stats.avgRevenue)}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Growth Rate</div>
          <div className={`stat-value ${stats.growth >= 0 ? 'stat-success' : 'stat-danger'}`}>
            {formatPercent(stats.growth)}
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Transactions</div>
          <div className="stat-value stat-warning">{stats.totalTransactions}</div>
        </div>
      </div>

      <div className="controls">
        <div className="filter-buttons">
          {['3m', '6m', '12m'].map((range) => (
            <button
              key={range}
              className={`filter-btn ${timeRange === range ? 'active' : ''}`}
              onClick={() => handleTimeRangeChange(range)}
            >
              {range.toUpperCase()}
            </button>
          ))}
        </div>
      </div>

      {isPending && <div className="loading-indicator">Loading...</div>}

      <div className="chart-container">
        <div className="chart-header">
          <h3>Revenue Trend</h3>
        </div>
        <div className="chart-bars">
          {filteredData.map((data, index) => {
            const maxRevenue = Math.max(...filteredData.map((d) => d.revenue));
            const height = (data.revenue / maxRevenue) * 100;
            return (
              <div key={index} className="chart-bar-wrapper">
                <div className="chart-bar" style={{ height: `${height}%` }}>
                  <span className="chart-value">{formatAmount(data.revenue)}</span>
                </div>
                <span className="chart-label">{data.period.split(' ')[0]}</span>
              </div>
            );
          })}
        </div>
      </div>

      <div className="data-grid">
        <table className="data-table">
          <thead>
            <tr>
              <th>Period</th>
              <th>Revenue</th>
              <th>Transactions</th>
              <th>Avg Transaction Value</th>
            </tr>
          </thead>
          <tbody>
            {filteredData.map((data, index) => (
              <tr key={index}>
                <td>{data.period}</td>
                <td className="amount">{formatAmount(data.revenue)}</td>
                <td>{data.transactions}</td>
                <td>{formatAmount(data.avgValue)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="toast-container">
        {toasts.map((toast) => (
          <div key={toast.id} className={`toast toast-${toast.type}`}>
            {toast.message}
          </div>
        ))}
      </div>
    </div>
  );
};

export default App;
