import { Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { useEffect } from 'react';
import { motion } from 'framer-motion';
import { useStore } from './store/useStore';
import { apiGet } from './utils/api';
import { getThemeClasses, getThemeHueShift } from './utils/theme';
import DarkVeil from './components/DarkVeil';
import { Navbar } from './components/Navbar';
import { LoginPage } from './pages/LoginPage';
import { DashboardPage } from './pages/DashboardPage';
import { CallbackPage } from './pages/CallbackPage';
import { LastListenedPage } from './pages/LastListenedPage';
import { MixedPlaylistPage } from './pages/MixedPlaylistPage';
import { MemoryLanePage } from './pages/MemoryLanePage';
import LiveDashboardPage from './pages/LiveDashboardPage';

function App() {
  const { currentUser, partnerUser, isLoading, theme } = useStore();
  const location = useLocation();
  
  console.log('🔍 App - Current location:', location.pathname);

  useEffect(() => {
    // Initialize theme
    getThemeClasses(theme);
  }, [theme]);

  useEffect(() => {
    // Check for stored authentication tokens on app load
    const storedUser = localStorage.getItem('spotify-user');
    const storedPartner = localStorage.getItem('spotify-partner');
    
    if (storedUser) {
      try {
        const userData = JSON.parse(storedUser);
        useStore.getState().setCurrentUser(userData);
      } catch (error) {
        console.error('Failed to parse stored user data:', error);
        localStorage.removeItem('spotify-user');
      }
    }
    
    if (storedPartner) {
      try {
        const partnerData = JSON.parse(storedPartner);
        useStore.getState().setPartnerUser(partnerData);
      } catch (error) {
        console.error('Failed to parse stored partner data:', error);
        localStorage.removeItem('spotify-partner');
      }
    }
  }, []);

  useEffect(() => {
    // After login, if no partner in state, try to load partner from backend
    const loadPartner = async () => {
      const uid = useStore.getState().currentUser?.user?.id;
      if (!uid) return;
      if (useStore.getState().partnerUser) return;
      try {
        const partner = await apiGet<{ partnerId: string | null }>(`/partners/partner/${uid}`);
        if (partner.partnerId) {
          // hydrate minimal partner profile and recent data
          const [userProfile, recentlyPlayed, topTracks] = await Promise.all([
            apiGet(`/users/${partner.partnerId}`),
            apiGet(`/users/${partner.partnerId}/recently-played`),
            apiGet(`/users/${partner.partnerId}/top-tracks?time_range=short_term`),
          ]);
          useStore.getState().setPartnerUser({
            user: userProfile,
            accessToken: null,
            refreshToken: null,
            isAuthenticated: true,
            recentlyPlayed,
            topTracks: (topTracks as any[]).map((item: any) => item.track),
            topArtists: [],
          } as any);
        }
      } catch {}
    };
    loadPartner();
  }, [currentUser?.user?.id]);

  const isAuthenticated = currentUser?.isAuthenticated || false;

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center relative">
        <DarkVeil hueShift={getThemeHueShift(theme)} />
        <motion.div
          initial={{ opacity: 0, scale: 0.8 }}
          animate={{ opacity: 1, scale: 1 }}
          className="glass-fluid rounded-3xl p-10 flex flex-col items-center space-y-6 relative z-20"
        >
          <div className="w-16 h-16 border-4 border-t-transparent rounded-full animate-spin" style={{ borderColor: `var(--theme-primary) var(--theme-primary) var(--theme-primary) transparent` }}></div>
          <p className="text-white font-medium text-lg">Loading your musical journey...</p>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="min-h-screen relative overflow-hidden">
      <DarkVeil hueShift={getThemeHueShift(theme)} />
      
      <div className="relative z-20">
        {isAuthenticated && <Navbar />}
        
        <Routes>
          <Route 
            path="/" 
            element={
              isAuthenticated ? (
                <DashboardPage />
              ) : (
                <LoginPage />
              )
            } 
          />
          
          <Route 
            path="/callback" 
            element={<CallbackPage />} 
          />
          
          <Route 
            path="/callback.html" 
            element={<CallbackPage />} 
          />
          
          {isAuthenticated && (
            <>
              <Route path="/last-listened" element={<LastListenedPage />} />
              <Route path="/mixed-playlist" element={<MixedPlaylistPage />} />
              <Route path="/memory-lane" element={<MemoryLanePage />} />
              <Route path="/live" element={<LiveDashboardPage />} />
            </>
          )}
          
          <Route path="*" element={<Navigate to="/" replace />} />
        </Routes>
      </div>
    </div>
  );
}

export default App;
