'use client';
import { Box, CircularProgress, Typography } from '@mui/material';

import { useEffect, useRef, useState } from 'react';
import { useAuthStore } from '../store/useAuthStore';
import { loginService } from '../services/login.service';
import { profileService } from '../../profile/services/profile.service';
import { mapToSafeProfile } from '../utils/mappers';

export function AuthInitializer({ children }: { children: React.ReactNode }) {
  const { setUser, logout } = useAuthStore();
  const initialized = useRef(false);
  const [isChecking, setIsChecking] = useState(true);

  useEffect(() => {
    if (initialized.current) return;
    initialized.current = true;

    const validateSession = async () => {
      try {
        await loginService.refreshToken();

        const profile = await profileService.obterColaboradorAtual();
        setUser(mapToSafeProfile(profile));
      } catch (error) {
        console.warn('Sessão expirada ou inválida', error);
        logout();
      } finally {
        setIsChecking(false);
      }
    };

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

  if (isChecking) {
    return (
      <Box
        sx={{
          display: 'flex',
          height: '100vh',
          width: '100vw',
          alignItems: 'center',
          justifyContent: 'center',
          bgcolor: 'background.default',
        }}
      >
        <Box
          sx={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gap: 2,
            position: 'relative',
          }}
        >
          <Box sx={{ position: 'relative', display: 'flex' }}>
            <CircularProgress
              variant="determinate"
              sx={{
                color: (theme) => theme.palette.grey[200],
              }}
              size={48}
              thickness={4}
              value={100}
            />
            <CircularProgress
              variant="indeterminate"
              disableShrink
              sx={{
                color: (theme) => theme.palette.primary.main,
                animationDuration: '550ms',
                position: 'absolute',
                left: 0,
                [`& .MuiCircularProgress-circle`]: {
                  strokeLinecap: 'round',
                },
              }}
              size={48}
              thickness={4}
            />
          </Box>
          <Typography variant="body2" color="textSecondary">
            Validando acesso...
          </Typography>
        </Box>
      </Box>
    );
  }

  return <>{children}</>;
}
