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";
import { dbManager } from "../utils/indexedDB";

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

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const authStatus = await authApi.checkStatus();
        if (authStatus.authenticated) {
          const newUserId = authStatus.userId!;
          
          // Если пользователь изменился, очищаем IndexedDB
          if (currentUserId && currentUserId !== newUserId) {
            console.log(`[ProtectedRoute] User changed from ${currentUserId} to ${newUserId}, clearing IndexedDB`);
            await dbManager.clearAll();
          }
          
          dispatch(
            setAuth({
              userId: newUserId,
              username: authStatus.username!,
            })
          );
        } else {
          dispatch(clearAuth());
        }
      } catch {
        dispatch(clearAuth());
      } finally {
        setIsChecking(false);
      }
    };

    // Всегда проверяем статус аутентификации при монтировании,
    // независимо от начального состояния Redux (localStorage может быть устаревшим)
    checkAuth();
  }, [dispatch, currentUserId]);

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

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