import React, { useState, useEffect } from 'react';
import { Routes, Route, Navigate, useNavigate, useLocation } from 'react-router-dom';
import Navbar from './components/Navbar';
import Tracker from './components/Tracker/index';
import History from './components/History';
import Stats from './components/Stats';
import AICoach from './components/AICoach';
import Plans from './components/Plans';
import Login from './components/Login';
import Profile from './components/Profile';
import InitializeAccount from './components/InitializeAccount';
import { Language, User } from './types';
import { getSystemLanguage } from './services/i18n';
import { useAuth } from './context/AuthContext';

function App() {
  const { currentUser, updateUser, logout, isLoading } = useAuth();

  const [language, setLanguage] = useState<Language>('en');
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    if (currentUser?.profile?.language) {
      setLanguage(currentUser.profile.language as Language);
    } else {
      setLanguage(getSystemLanguage());
    }
  }, [currentUser]);

  const handleLogin = (user: User) => {
    updateUser(user);
    navigate('/');
  };

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  if (isLoading) {
    return (
      <div className="h-[100dvh] w-screen bg-surface flex items-center justify-center text-on-surface">
        <div className="animate-pulse">Loading...</div>
      </div>
    );
  }

  if (!currentUser && location.pathname !== '/login') {
    return <Navigate to="/login" />;
  }

  if (currentUser?.isFirstLogin && location.pathname !== '/initialize') {
    return <Navigate to="/initialize" />;
  }

  return (
    <div className="h-[100dvh] w-screen bg-surface text-on-surface font-sans flex flex-col md:flex-row overflow-hidden">
      {currentUser && (
        <Navbar lang={language} />
      )}

      {/* Main Content Area */}
      <main className="flex-1 h-full relative w-full max-w-5xl mx-auto md:px-4">
        <div className="h-full w-full pb-20 md:pb-0 bg-surface">
          <Routes>
            <Route path="/login" element={
              !currentUser ? (
                <Login onLogin={handleLogin} language={language} onLanguageChange={setLanguage} />
              ) : (
                <Navigate to="/" />
              )
            } />
            <Route path="/initialize" element={
              currentUser && currentUser.isFirstLogin ? (
                <InitializeAccount
                  onInitialized={updateUser}
                  language={language}
                  onLanguageChange={setLanguage}
                />
              ) : (
                <Navigate to="/" />
              )
            } />
            <Route path="/" element={
              <Tracker lang={language} />
            } />
            <Route path="/plans" element={
              <Plans lang={language} />
            } />
            <Route path="/history" element={
              <History lang={language} />
            } />
            <Route path="/stats" element={
              <Stats lang={language} />
            } />
            <Route path="/coach" element={
              <AICoach lang={language} />
            } />
            <Route path="/profile" element={
              <Profile
                user={currentUser}
                onLogout={handleLogout}
                lang={language}
                onLanguageChange={setLanguage}
                onUserUpdate={updateUser}
              />
            } />
            <Route path="*" element={<Navigate to="/" />} />
          </Routes>
        </div>
      </main>
    </div>
  );
}

export default App;
