import { type ReactNode, useEffect, useRef, useState } from 'react';
import { Box, CircularProgress, Typography } from '@mui/material';
import keycloak from '../../services/keycloak';
import { LoginPage } from '../LoginPage';

interface AuthProviderProps {
  children: ReactNode;
}

export function AuthProvider({ children }: AuthProviderProps) {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const didInit = useRef(false);

  useEffect(() => {
    // Предотвращаем двойную инициализацию в StrictMode
    if (didInit.current) {
      return;
    }
    didInit.current = true;

    let refreshInterval: ReturnType<typeof setInterval> | null = null;

    const initKeycloak = async () => {
      try {
        const authenticated = await keycloak.init({
          onLoad: 'check-sso',
          checkLoginIframe: false,
          pkceMethod: 'S256',
        });

        setIsAuthenticated(authenticated);

        if (authenticated) {
          // Автоматическое обновление токена
          refreshInterval = setInterval(() => {
            keycloak.updateToken(30).catch(() => {
              console.error('Failed to refresh token');
              void keycloak.login();
            });
          }, 10000);
        }
      } catch (error) {
        console.error('Keycloak init failed:', error);
        setIsAuthenticated(false);
      } finally {
        setIsLoading(false);
      }
    };

    void initKeycloak();

    return () => {
      if (refreshInterval) {
        clearInterval(refreshInterval);
      }
    };
  }, []);

  if (isLoading) {
    return (
      <Box
        sx={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          height: '100vh',
          gap: 2,
        }}
      >
        <CircularProgress />
        <Typography>Авторизация...</Typography>
      </Box>
    );
  }

  if (!isAuthenticated) {
    return <LoginPage />;
  }

  return <>{children}</>;
}
