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

interface SalesMetric {
  id: string;
  stage: string;
  revenue: number;
  deals: number;
  avgDealSize: number;
  winRate: number;
  velocity: number;
}

const mockMetrics: SalesMetric[] = [
  { id: '1', stage: 'Prospecting', revenue: 150000, deals: 15, avgDealSize: 10000, winRate: 15, velocity: 12 },
  { id: '2', stage: 'Qualified', revenue: 280000, deals: 14, avgDealSize: 20000, winRate: 28, velocity: 18 },
  { id: '3', stage: 'Proposal', revenue: 350000, deals: 10, avgDealSize: 35000, winRate: 42, velocity: 25 },
  { id: '4', stage: 'Negotiation', revenue: 420000, deals: 7, avgDealSize: 60000, winRate: 68, velocity: 32 },
  { id: '5', stage: 'Closed Won', revenue: 520000, deals: 13, avgDealSize: 40000, winRate: 100, velocity: 45 },
];

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;
};

interface Toast {
  id: number;
  message: string;
  type: 'success' | 'error' | 'info';
}

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

const App = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedMetric, setSelectedMetric] = useState<SalesMetric | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, addToast } = useToast();

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredMetrics = useMemo(() => {
    if (!debouncedSearch) return mockMetrics;
    const term = debouncedSearch.toLowerCase();
    return mockMetrics.filter(m => m.stage.toLowerCase().includes(term));
  }, [debouncedSearch]);

  const stats = useMemo(() => ({
    totalRevenue: mockMetrics.reduce((sum, m) => sum + m.revenue, 0),
    totalDeals: mockMetrics.reduce((sum, m) => sum + m.deals, 0),
    avgWinRate: (mockMetrics.reduce((sum, m) => sum + m.winRate, 0) / mockMetrics.length).toFixed(0),
    avgVelocity: (mockMetrics.reduce((sum, m) => sum + m.velocity, 0) / mockMetrics.length).toFixed(0),
  }), []);

  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    startTransition(() => {
      setSearchTerm(e.target.value);
    });
  };

  const handleSelectMetric = (metric: SalesMetric) => {
    setSelectedMetric(metric);
    addToast(`Viewing ${metric.stage} metrics`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Sales Dashboard</h1>
        <p>Revenue by stage, deal velocity, win rate</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Revenue</div>
          <div className="stat-value">${(stats.totalRevenue / 1000).toFixed(0)}K</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Deals</div>
          <div className="stat-value">{stats.totalDeals}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Avg Win Rate</div>
          <div className="stat-value">{stats.avgWinRate}%</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Avg Velocity (days)</div>
          <div className="stat-value">{stats.avgVelocity}</div>
        </div>
      </div>

      <div className="search-bar">
        <input
          type="text"
          placeholder="Search stages..."
          value={searchTerm}
          onChange={handleSearch}
          className="search-input"
        />
        {isPending && <span className="search-loading">Searching...</span>}
      </div>

      {filteredMetrics.length === 0 ? (
        <div className="empty-state">
          <h3>No metrics found</h3>
          <p>Try adjusting your search criteria</p>
        </div>
      ) : (
        <div className="data-grid">
          <table className="data-table">
            <thead>
              <tr>
                <th>Stage</th>
                <th>Revenue</th>
                <th>Deals</th>
                <th>Avg Deal Size</th>
                <th>Win Rate</th>
                <th>Velocity (days)</th>
              </tr>
            </thead>
            <tbody>
              {filteredMetrics.map(metric => (
                <tr
                  key={metric.id}
                  onClick={() => handleSelectMetric(metric)}
                  className={selectedMetric?.id === metric.id ? 'selected' : ''}
                >
                  <td>{metric.stage}</td>
                  <td>${(metric.revenue / 1000).toFixed(0)}K</td>
                  <td>{metric.deals}</td>
                  <td>${(metric.avgDealSize / 1000).toFixed(0)}K</td>
                  <td>{metric.winRate}%</td>
                  <td>{metric.velocity}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedMetric && (
        <div className="detail-panel">
          <h3>Stage Metrics</h3>
          <div className="detail-grid">
            <div><strong>Stage:</strong> {selectedMetric.stage}</div>
            <div><strong>Revenue:</strong> ${selectedMetric.revenue.toLocaleString()}</div>
            <div><strong>Deals:</strong> {selectedMetric.deals}</div>
            <div><strong>Avg Deal Size:</strong> ${selectedMetric.avgDealSize.toLocaleString()}</div>
            <div><strong>Win Rate:</strong> {selectedMetric.winRate}%</div>
            <div><strong>Velocity:</strong> {selectedMetric.velocity} days</div>
          </div>
        </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;
