import React, { useEffect, useState } from "react";
import { Navigate } from "react-router-dom";
import { useAppSelector, useAppDispatch } from "../store/hooks";
import { setAuth, clearAuth } from "../store/slices/authSlice";
import { authApi } from "../api/authApi";
import { LoadingOverlay } from "./common/LoadingOverlay";

export const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const isAuthenticated = useAppSelector((state) => state.auth.isAuthenticated);
  const dispatch = useAppDispatch();
  const [isChecking, setIsChecking] = useState(true);

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const authStatus = await authApi.checkStatus();
        if (authStatus.authenticated) {
          dispatch(
            setAuth({
              userId: authStatus.userId!,
              username: authStatus.username!,
            })
          );
        } else {
          dispatch(clearAuth());
        }
      } catch {
        dispatch(clearAuth());
      } finally {
        setIsChecking(false);
      }
    };

    if (isAuthenticated) {
      checkAuth();
    } else {
      setIsChecking(false);
    }
  }, [dispatch, isAuthenticated]);

  if (isChecking) {
    return <LoadingOverlay />;
  }

  return isAuthenticated ? <>{children}</> : <Navigate to="/" replace />;
};
