import React, { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Container, Box, Button, Typography } from "@mui/material";
import { useMsal } from "@azure/msal-react";
import { toast } from "react-toastify";
import { loginRequest } from "../authConfig.js";
import ssoIcon from "../assets/images/microsoft-sso-icon.png";
import useApiService from "../services/apiService.js";
import { getRoleDetails, userRolesPermissions } from "../constants/apiEndPoints.js";
import { useUser } from "../context/UserContext.js"
import { userStatus, permissionTypes } from "../constants/userConstants.js";

function SignIn() {
  const { instance, accounts } = useMsal();
  const { postApi } = useApiService()
  const navigate = useNavigate();
  const { login, logout, setUserPermissions } = useUser()

  const handleLogin = async () => {
    if (!accounts?.length > 0) {
      instance.loginRedirect(loginRequest)
    }
  };

  useEffect(() => {
    if (accounts?.length > 0) {
      postApi(userRolesPermissions).then(res => {
        if(res?.Records && (res?.Records?.[0]?.user_status !== userStatus.Deleted.key || res?.Records?.[0]?.user_status !== userStatus.Deactive.key)){
          login(res?.Records[0]);
          postApi(getRoleDetails, {"Email": res?.Records[0].user_email, "RoleId": `${res?.Records[0].user_role_id}`}).then(response => {
            if(response?.Records) {
              handlePermissions(response.Records)
            } else {
              toast.error("Something wrong with permissions")
            }
          })
        }
        else{
          toast.error("You are not authorized to view this application")
          localStorage.clear()  
          logout();
          instance.logoutPopup()
        }
      })
    }
  }, [accounts, navigate]);

  const handlePermissions = async (apiPermissions) => { 
    const res = await setUserPermissions(apiPermissions);
    const result = res?.find(obj => 
      (Number.parseInt(obj.Permission_Id) === Number.parseInt(permissionTypes[0].key) || 
       Number.parseInt(obj.Permission_Id) === Number.parseInt(permissionTypes[1].key)) && 
      obj.ShowInMenu
    );
    navigate(result?.Path || "/dashboard");
  }

  return (
    <div className="outer-login">
      <Container component="main" maxWidth="xs" className="signin-container">
        <Box
          sx={{
            marginTop: 8,
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
          }}
        >
          <Typography className="title" component="h1" variant="h5">
            COMPUTRACE TRACKING
          </Typography>
          <Box sx={{ mt: 1 }}>
            <Button
              className="signin-btn"
              fullWidth
              variant="contained"
              color="primary"
              onClick={handleLogin}
              sx={{ mt: 3, mb: 2 }}
            >
              <img
                src={ssoIcon}
                alt="Microsoft Logo"
                style={{ width: "20px", height: "20px", marginRight: "8px" }}
              /> Sign In with Microsoft
            </Button>
          </Box>
        </Box>
      </Container>
    </div>
  );
}

export default SignIn;
