import React, { useEffect, useState } from "react";
import { Navigate } from "react-router-dom";
import { getSession } from "../api/userApi";

const ProtectedRoute = ({ user, setUser, children }) => {
  const [loading, setLoading] = useState(true);
  const [allowed, setAllowed] = useState(false);

  useEffect(() => {
    const validateSession = async () => {
      try {
        if (user) {
          setAllowed(true);
          return;
        }

        const data = await getSession();
        setUser(data.user);
        setAllowed(true);
      } catch (error) {
        setAllowed(false);
      } finally {
        setLoading(false);
      }
    };

    validateSession();
  }, [user, setUser]);

  if (loading) {
    return <div className="min-h-screen bg-secondary p-6 text-primary">Loading...</div>;
  }

  if (!allowed) {
    return <Navigate to="/login" replace />;
  }

  return children;
};

export default ProtectedRoute;
