import React from 'react';
import { Dialog, DialogTitle, DialogContent, DialogActions, Button } from "@mui/material";
import { useMsal } from '@azure/msal-react';
import MainContainer from './components/MainContainer.js';
import { useTokenExpiryMonitor } from "./hooks/useTokenExpiryMonitor.js";
import useApiService from "./services/apiService.js";
import './App.css';

function App() {
  const { instance } = useMsal();
  const { RoleChangedPopupElement } = useApiService();

  const logout = () => {
    instance.logoutRedirect();
  };

  const {
    showDialog,
    countdown,
    handleRenew,
    handleExpire,
  } = useTokenExpiryMonitor({
    onRenew: () => console.log("Token renewed!"),
    onExpire: logout,
  });

  const formatCountdown = (seconds) => {
    const m = String(Math.floor(seconds / 60)).padStart(2, '0');
    const s = String(seconds % 60).padStart(2, '0');
    return `${m}:${s}`;
  };

  return (
    <>
      <MainContainer />
      {RoleChangedPopupElement}
      {showDialog && (
        <Dialog open>
          <DialogTitle>Session Expiring</DialogTitle>
          <DialogContent>
            Your session is about to expire. Would you like to extend it?
            <div style={{marginTop: "10px", fontSize: "13px"}}>
             <b>Note:</b> If you don’t take any action, you will be automatically logged out in <b style={{ color: "green"}}>{formatCountdown(countdown)}</b>
            </div>
          </DialogContent>
          <DialogActions>
            <Button onClick={handleExpire}>No, Logout</Button>
            <Button onClick={handleRenew} autoFocus>Yes, Extend</Button>
          </DialogActions>
        </Dialog>
      )}
    </>
  );
}

export default App;
