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

interface AnalyticsData {
  id: string;
  source: string;
  pageViews: number;
  uniqueVisitors: number;
  conversions: number;
  bounceRate: number;
  avgSessionDuration: number;
}

const mockAnalytics: AnalyticsData[] = [
  { id: '1', source: 'Organic Search', pageViews: 45000, uniqueVisitors: 12000, conversions: 480, bounceRate: 42, avgSessionDuration: 185 },
  { id: '2', source: 'Direct', pageViews: 23000, uniqueVisitors: 8500, conversions: 340, bounceRate: 38, avgSessionDuration: 220 },
  { id: '3', source: 'Social Media', pageViews: 18000, uniqueVisitors: 6200, conversions: 186, bounceRate: 55, avgSessionDuration: 95 },
  { id: '4', source: 'Referral', pageViews: 12000, uniqueVisitors: 4100, conversions: 164, bounceRate: 48, avgSessionDuration: 145 },
  { id: '5', source: 'Email', pageViews: 8500, uniqueVisitors: 3200, conversions: 256, bounceRate: 35, avgSessionDuration: 210 },
];

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 [selectedSource, setSelectedSource] = useState<AnalyticsData | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, addToast } = useToast();

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredAnalytics = useMemo(() => {
    if (!debouncedSearch) return mockAnalytics;
    const term = debouncedSearch.toLowerCase();
    return mockAnalytics.filter(a => a.source.toLowerCase().includes(term));
  }, [debouncedSearch]);

  const stats = useMemo(() => ({
    totalPageViews: mockAnalytics.reduce((sum, a) => sum + a.pageViews, 0),
    totalVisitors: mockAnalytics.reduce((sum, a) => sum + a.uniqueVisitors, 0),
    totalConversions: mockAnalytics.reduce((sum, a) => sum + a.conversions, 0),
    avgBounceRate: (mockAnalytics.reduce((sum, a) => sum + a.bounceRate, 0) / mockAnalytics.length).toFixed(0),
  }), []);

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

  const handleSelectSource = (source: AnalyticsData) => {
    setSelectedSource(source);
    addToast(`Viewing ${source.source}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Analytics Hub</h1>
        <p>Traffic sources, page views, conversion rates</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Page Views</div>
          <div className="stat-value">{(stats.totalPageViews / 1000).toFixed(0)}K</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Unique Visitors</div>
          <div className="stat-value">{(stats.totalVisitors / 1000).toFixed(1)}K</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Conversions</div>
          <div className="stat-value">{stats.totalConversions}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Avg Bounce Rate</div>
          <div className="stat-value">{stats.avgBounceRate}%</div>
        </div>
      </div>

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

      {filteredAnalytics.length === 0 ? (
        <div className="empty-state">
          <h3>No data found</h3>
          <p>Try adjusting your search criteria</p>
        </div>
      ) : (
        <div className="data-grid">
          <table className="data-table">
            <thead>
              <tr>
                <th>Source</th>
                <th>Page Views</th>
                <th>Visitors</th>
                <th>Conversions</th>
                <th>Bounce Rate</th>
                <th>Avg Session (s)</th>
              </tr>
            </thead>
            <tbody>
              {filteredAnalytics.map(source => (
                <tr
                  key={source.id}
                  onClick={() => handleSelectSource(source)}
                  className={selectedSource?.id === source.id ? 'selected' : ''}
                >
                  <td>{source.source}</td>
                  <td>{source.pageViews.toLocaleString()}</td>
                  <td>{source.uniqueVisitors.toLocaleString()}</td>
                  <td>{source.conversions}</td>
                  <td>{source.bounceRate}%</td>
                  <td>{source.avgSessionDuration}s</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedSource && (
        <div className="detail-panel">
          <h3>Source Details</h3>
          <div className="detail-grid">
            <div><strong>Source:</strong> {selectedSource.source}</div>
            <div><strong>Page Views:</strong> {selectedSource.pageViews.toLocaleString()}</div>
            <div><strong>Unique Visitors:</strong> {selectedSource.uniqueVisitors.toLocaleString()}</div>
            <div><strong>Conversions:</strong> {selectedSource.conversions}</div>
            <div><strong>Bounce Rate:</strong> {selectedSource.bounceRate}%</div>
            <div><strong>Avg Session Duration:</strong> {selectedSource.avgSessionDuration}s</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;
