// src/hooks/useAppInitialization.ts
import { useState, useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from './useAuth';
import { useModal } from './useModal';
import { logger } from '../services/logger.client';
import config from '../config';

export const useAppInitialization = () => {
  const { userProfile, login } = useAuth();
  const { openModal } = useModal();
  const location = useLocation();
  const navigate = useNavigate();

  const [isDarkMode, setIsDarkMode] = useState(false);
  const [unitSystem, setUnitSystem] = useState<'metric' | 'imperial'>('imperial');

  // Effect to handle the token from Google/GitHub OAuth redirect
  useEffect(() => {
    const urlParams = new URLSearchParams(location.search);
    const googleToken = urlParams.get('googleAuthToken');

    if (googleToken) {
      logger.info('Received Google Auth token from URL. Authenticating...');
      login(googleToken).catch((err) =>
        logger.error('Failed to log in with Google token', { error: err }),
      );
      navigate(location.pathname, { replace: true });
    }

    const githubToken = urlParams.get('githubAuthToken');
    if (githubToken) {
      logger.info('Received GitHub Auth token from URL. Authenticating...');
      login(githubToken).catch((err) => {
        logger.error('Failed to log in with GitHub token', { error: err });
      });
      navigate(location.pathname, { replace: true });
    }
  }, [login, location.search, navigate, location.pathname]);

  // Effect to handle "What's New" modal
  useEffect(() => {
    const appVersion = config.app.version;
    if (appVersion) {
      logger.info(`Application version: ${appVersion}`);
      const lastSeenVersion = localStorage.getItem('lastSeenVersion');
      if (appVersion !== lastSeenVersion) {
        openModal('whatsNew');
        localStorage.setItem('lastSeenVersion', appVersion);
      }
    }
  }, [openModal]);

  // Effect to set initial theme based on user profile, local storage, or system preference
  useEffect(() => {
    let darkModeValue: boolean;
    if (userProfile && userProfile.preferences?.darkMode !== undefined) {
      // Preference from DB
      darkModeValue = userProfile.preferences.darkMode;
    } else {
      // Fallback to local storage or system preference
      const savedMode = localStorage.getItem('darkMode');
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      darkModeValue = savedMode !== null ? savedMode === 'true' : prefersDark;
    }
    setIsDarkMode(darkModeValue);
    document.documentElement.classList.toggle('dark', darkModeValue);
    // Also save to local storage if coming from profile, to persist on logout
    if (userProfile && userProfile.preferences?.darkMode !== undefined) {
      localStorage.setItem('darkMode', String(userProfile.preferences.darkMode));
    }
  }, [userProfile]);

  // Effect to set initial unit system based on user profile or local storage
  useEffect(() => {
    if (userProfile && userProfile.preferences?.unitSystem) {
      setUnitSystem(userProfile.preferences.unitSystem);
      localStorage.setItem('unitSystem', userProfile.preferences.unitSystem);
    } else {
      const savedSystem = localStorage.getItem('unitSystem') as 'metric' | 'imperial' | null;
      if (savedSystem) {
        setUnitSystem(savedSystem);
      }
    }
  }, [userProfile?.preferences?.unitSystem, userProfile?.user.user_id]);

  return { isDarkMode, unitSystem };
};
