// Main App component

import { useState, useCallback } from 'react';
import Header from './components/Header';
import StatisticsCards from './components/StatisticsCards';
import EventFeed from './components/EventFeed';
import { useWebSocket } from './hooks/useWebSocket';
import { useEvents } from './hooks/useEvents';
import { useStatistics } from './hooks/useStatistics';
import type { FilterType, Event, Statistics } from './types';
import { EVENT_FILTER_MAP } from './types';
import './styles/index.css';

function App() {
  const [activeFilter, setActiveFilter] = useState<FilterType>('ALL');

  // Get event types for current filter
  const eventTypes = EVENT_FILTER_MAP[activeFilter];

  // Hooks
  const { statistics, updateStatistics, reset: resetStats } = useStatistics();
  const { events, addEvent, clearEvents, hasMore, loadMore } = useEvents(eventTypes);

  // WebSocket connection
  const handleNewEvent = useCallback(
    (event: Event) => {
      // Only add event if it matches current filter
      if (eventTypes.includes(event.event_type)) {
        addEvent(event);
      }
    },
    [eventTypes, addEvent]
  );

  const handleStatsUpdate = useCallback(
    (stats: Statistics) => {
      updateStatistics(stats);
    },
    [updateStatistics]
  );

  const { isConnected } = useWebSocket(handleNewEvent, handleStatsUpdate);

  // Handle reset stats
  const handleResetStats = useCallback(async () => {
    if (confirm('Are you sure you want to reset all statistics? This will delete all events.')) {
      await resetStats();
      clearEvents();
    }
  }, [resetStats, clearEvents]);

  // Handle filter change
  const handleFilterChange = useCallback((filter: FilterType) => {
    setActiveFilter(filter);
  }, []);

  return (
    <div className="app">
      <Header isConnected={isConnected} onResetStats={handleResetStats} />

      <main className="main-content">
        <StatisticsCards statistics={statistics} />

        <EventFeed
          events={events}
          loading={false}
          activeFilter={activeFilter}
          onFilterChange={handleFilterChange}
          onLoadMore={loadMore}
          hasMore={hasMore}
        />
      </main>
    </div>
  );
}

export default App;
