import React, { useEffect, useState } from 'react';
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Navigate,
} from 'react-router-dom';
import Lobby from './components/Lobby';
import VotingTable from './components/VotingTable';
import UserSessionListener from './components/UserSessionListener';
import axios from 'axios';
import cyarenLogo from './assets/images/CyarenLogo.png';
import cardLogo from './assets/images/logo.png';
import styles from './App.module.css';

const App = () => {
  const [userId, setUserId] = useState('');
  const [loading, setLoading] = useState(true);

  const handleJoinSession = (userId) => {
    setUserId(userId);
    return true;
  };

  useEffect(() => {
    // Check if there's a user session by making a request to the backend
    axios
      .get('/api/auth/session')
      .then((response) => {
        const { userId } = response.data;
        if (userId) {
          setUserId(userId); // User is logged in
        } else {
          // If no user session exists, create an anonymous user session
          axios
            .post('/api/auth/signin-anonymous')
            .then((response) => {
              setUserId(response.data.userId);
            })
            .catch((error) => {
              console.error('Error signing in anonymously:', error);
            });
        }
      })
      .catch((error) => {
        console.error('Error checking user session:', error);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  return (
    <Router>
      <UserSessionListener />
      <div className={styles.app}>
        <section className={styles.header}>
          <Routes>
            <Route
              path="/lobby/:sessionId?"
              element={<Lobby onJoinSession={handleJoinSession} />}
              loading={loading}
            />
            <Route
              path="/session/:sessionId"
              element={<VotingTable userId={userId} />}
            />
            <Route path="*" element={<Navigate to={`/lobby`} />} />
          </Routes>
        </section>
        <section className={styles.footer}>
          <div className={styles.logoEnvelope}>
            <img className={styles.cyaren} src={cyarenLogo} alt="cyaren-logo" />
          </div>
          <img
            className={`${styles.cardLogo} ${styles.moveLeft}`}
            src={cardLogo}
            alt="card-logo"
          />
          <img
            className={`${styles.cardLogo} ${styles.moveRight}`}
            src={cardLogo}
            alt="card-logo"
          />
        </section>
      </div>
    </Router>
  );
};

export default App;
