import { useState, useEffect, useCallback } from 'react';
import { 
  CalendarState, 
  UseCalendarOptions, 
  UseCalendarReturn, 
  CalendarView, 
  Event, 
  TrendingEvent, 
  UserLocation 
} from './types';
import { trendingAnalyticsService } from '../../lib/analytics';
import { geolocationService } from '../../lib/geolocation';

/**
 * Custom hook for calendar state management
 */
export const useCalendar = (options: UseCalendarOptions = {}): UseCalendarReturn => {
  const {
    initialView = 'month',
    showLocationFeatures = false,
    showTrending = false,
    events: initialEvents = []
  } = options;

  const [state, setState] = useState<CalendarState>({
    currentDate: new Date(),
    view: initialView,
    events: initialEvents,
    filteredEvents: initialEvents,
    trendingEvents: [],
    nearbyEvents: [],
    userLocation: null,
    isLoading: false,
    isMobile: false
  });

  // Detect mobile screen size
  useEffect(() => {
    const checkMobile = () => {
      setState(prev => ({ ...prev, isMobile: window.innerWidth < 768 }));
    };
    
    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  // Update events when prop changes
  useEffect(() => {
    setState(prev => ({
      ...prev,
      events: initialEvents,
      filteredEvents: initialEvents
    }));
  }, [initialEvents]);

  // Load location and trending data
  const loadLocationAndTrending = useCallback(async () => {
    if (!showLocationFeatures && !showTrending) return;

    setState(prev => ({ ...prev, isLoading: true }));
    
    try {
      // Get user location
      const location = await geolocationService.requestLocationPermission();
      if (location) {
        const userLocation: UserLocation = {
          lat: location.latitude, 
          lng: location.longitude,
          city: location.city,
          state: location.state || location.region,
          country: location.country || location.country_code,
          source: location.source as 'gps' | 'ip'
        };
        
        setState(prev => ({ ...prev, userLocation }));
        
        // Get trending events if enabled
        if (showTrending) {
          const trending = await trendingAnalyticsService.getTrendingEvents(
            location.latitude, 
            location.longitude, 
            50, 
            10
          );
          setState(prev => ({ ...prev, trendingEvents: trending }));
        }
        
        // Get nearby events if enabled
        if (showLocationFeatures) {
          const nearby = await trendingAnalyticsService.getHotEventsInArea(
            location.latitude, 
            location.longitude, 
            25, 
            8
          );
          setState(prev => ({ ...prev, nearbyEvents: nearby }));
        }
      }
    } catch (error) {
      console.error('Failed to load location and trending data:', error);
    } finally {
      setState(prev => ({ ...prev, isLoading: false }));
    }
  }, [showLocationFeatures, showTrending]);

  // Load location data on mount if features are enabled
  useEffect(() => {
    loadLocationAndTrending();
  }, [loadLocationAndTrending]);

  // Navigation functions
  const setCurrentDate = useCallback((date: Date) => {
    setState(prev => ({ ...prev, currentDate: date }));
  }, []);

  const setView = useCallback((view: CalendarView) => {
    setState(prev => ({ ...prev, view }));
  }, []);

  const previousMonth = useCallback(() => {
    setState(prev => ({
      ...prev,
      currentDate: new Date(prev.currentDate.getFullYear(), prev.currentDate.getMonth() - 1, 1)
    }));
  }, []);

  const nextMonth = useCallback(() => {
    setState(prev => ({
      ...prev,
      currentDate: new Date(prev.currentDate.getFullYear(), prev.currentDate.getMonth() + 1, 1)
    }));
  }, []);

  const goToToday = useCallback(() => {
    setState(prev => ({ ...prev, currentDate: new Date() }));
  }, []);

  return {
    ...state,
    setCurrentDate,
    setView,
    previousMonth,
    nextMonth,
    goToToday,
    loadLocationAndTrending
  };
};