import { useEffect } from 'react'
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom'
import { useAppDispatch, useAppSelector } from '@/hooks/useRedux'
import { setUser } from '@/stores/authSlice'
import { authService } from '@/services/api'

import LoginPage from './pages/Login'
import SignupPage from './pages/Signup'
import ChatPage from './pages/Chat'
import CallsPage from './pages/Calls'
import SettingsPage from './pages/Settings'
import AdminPage from './pages/Admin'
import ProfilePage from './pages/Profile'
import FriendsPage from './pages/Friends'
import ProtectedRoute from '@/components/ProtectedRoute'

function App() {
  const dispatch = useAppDispatch()
  const { isAuthenticated, isLoading } = useAppSelector((state) => state.auth)

  useEffect(() => {
    // Check if user is already logged in
    const checkAuth = async () => {
      const token = localStorage.getItem('token')
      if (token) {
        try {
          const response = await authService.getMe()
          dispatch(setUser(response.data))
        } catch (error) {
          localStorage.removeItem('token')
        }
      }
    }

    checkAuth()
  }, [dispatch])

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-900">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-4 border-purple-600 border-t-transparent"></div>
          <p className="text-white mt-4">Loading...</p>
        </div>
      </div>
    )
  }

  return (
    <Router>
      <Routes>
        {/* Public Routes */}
        <Route
          path="/login"
          element={isAuthenticated ? <Navigate to="/app" /> : <LoginPage />}
        />
        <Route
          path="/signup"
          element={isAuthenticated ? <Navigate to="/app" /> : <SignupPage />}
        />

        {/* Protected Routes */}
        <Route
          path="/app"
          element={<ProtectedRoute element={<ChatPage />} />}
        />
        <Route
          path="/calls"
          element={<ProtectedRoute element={<CallsPage />} />}
        />
        <Route
          path="/settings"
          element={<ProtectedRoute element={<SettingsPage />} />}
        />
        <Route
          path="/friends"
          element={<ProtectedRoute element={<FriendsPage />} />}
        />
        <Route
          path="/profile/:userId?"
          element={<ProtectedRoute element={<ProfilePage />} />}
        />
        <Route
          path="/admin"
          element={<ProtectedRoute element={<AdminPage />} />}
        />

        {/* Default redirect */}
        <Route path="/" element={<Navigate to={isAuthenticated ? '/app' : '/login'} />} />
      </Routes>
    </Router>
  )
}

export default App
