// src/components/Require2FA.jsx
import React, { useState, useEffect } from 'react';
import { Navigate } from 'react-router-dom';
import { Box, CircularProgress, Typography } from '@mui/material';
import axios from 'axios';
import { apiPath } from '../auth/utils';

const Require2FA = ({ children }) => {
  const [is2FAEnabled, setIs2FAEnabled] = useState(null); // null = loading
  const [error, setError] = useState(false);

  useEffect(() => {
    const check2FA = async () => {
      try {
        const response = await axios.get(`${apiPath}/2fa/status`, {
          headers: { Authorization: `Bearer ${localStorage.getItem('accessToken')}` }
        });
        setIs2FAEnabled(response.data.enabled);
      } catch (err) {
        // Fallback to localStorage (same logic as in Profile page)
        try {
          const userData = JSON.parse(localStorage.getItem('userData') || '{}');
          setIs2FAEnabled(!!userData.twoFactorEnabled);
        } catch {
          setError(true);
        }
      }
    };

    check2FA();
  }, []);

  if (is2FAEnabled === null) {
    // Still loading
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <CircularProgress />
        <Typography sx={{ ml: 2 }}>Checking security settings...</Typography>
      </Box>
    );
  }

  if (!is2FAEnabled || error) {
    // Redirect to profile page with a clear message
    return <Navigate to="/profile" replace state={{ require2FA: true }} />;
  }

  // 2FA is enabled → allow access
  return children;
};

export default Require2FA;