import React, { useEffect, useState, useCallback, useRef } from 'react';
import { Button, Grid } from '@mui/material';
import { Add } from '@mui/icons-material';
import { useOutletContext } from 'react-router-dom';
import PropTypes from 'prop-types';
import { getManageRole, getAllMenu, updateRolePermission, getRoleDetails } from '../../constants/apiEndPoints.js';
import useApiService from "../../services/apiService.js";
import CommonTable from '../../components/CommonTable.js';
import Loader from '../../components/Loader.js';
import ManageRolesPermissionsPopup from './ManageRolesPermissionsPopup.js';
import { useUser } from '../../context/UserContext.js';
import { permissionTypes, saveType } from '../../constants/userConstants.js';
import "./ManageRoles.css";


function ManageRoles(props) {
  const { permissionId } = useOutletContext();
  const isFullAccess = permissionId === `${permissionTypes[0].key}`;
  const { user } = useUser();
  const [popupOpen, setPopupOpen] = useState(false);
  const [editRole, setEditRole] = useState(null);
  const [allModules, setAllModules] = useState(null)
  const { getApi, postApi } = useApiService();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [actionType, setActionType] = useState(null);
  const [allRoles, setAllRoles] = useState([]);
  const [filter, setFilter] = useState({
    Email: user?.user_email || "",
    SortType: "ASC",
    RoleId: null,
    PageNumber: 1,
    PageSize: 50,
    SortColumn: "Role_Name",
    Status: true,
  });

  const handleSave = async (payload, type) => {
    const respone = await postApi(updateRolePermission, payload);
    setEditRole(respone?.Records[0] || null) 
    getRoleTable(filter);
    return (type === saveType.Save) ? respone?.Records[0]?.RoleId : respone?.Records;
  };

  const getAllModules = useCallback(async () => {
    const res = await getApi(getAllMenu);
    setAllModules(res?.Records || []);
  }, [getApi]);

  const getRoleTable = useCallback(async (updatedFilter) => {
    console.log('🟡 ManageRoles getRoleTable called:', { updatedFilter, timestamp: new Date().toISOString() });
    setLoading(true);
    try {
      const currentFilter = filter;
      const updatedFilterData = { ...currentFilter, ...updatedFilter };
      setFilter(updatedFilterData);
      const result = await postApi(getManageRole, updatedFilterData);
      setAllRoles(result?.Records || []);
      setData(result || []);
    } catch (error) {
      console.error("Error fetching role details:", error);
    } finally {
      setLoading(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [postApi, filter]);

  const getRoleData = async (roleId) => {
    const payload = {
      "Email": user?.user_email || "",
      "RoleId": `${roleId}`,
    }
    const res = await postApi(getRoleDetails, payload);
    return res.Records;
  };

  const handleClosePopup = () => {
    setPopupOpen(false);
  };
  
  // Use useRef to ensure initialization only happens once
  const hasInitialized = useRef(false);
  
  useEffect(() => {
    if (!hasInitialized.current) {
      hasInitialized.current = true;
      getRoleTable({});
      getAllModules();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // Only run once on mount - ref guard ensures no duplicates

  const columns = [
    { field: 'RoleName', headerName: 'Role Name', type: String, flex: 3 },
    { field: 'Status', headerName: 'Status', type: String, flex: 1 },
    { field: 'Permission', headerName: 'Permission', type: Element , flex: 2, sortable: false, disableColumnSelector: !isFullAccess  },
   
  ];

  const createRole = () => {
    handleClosePopup();
    setEditRole(null);
    setPopupOpen(true); 
    setActionType("addEdit");
  };

  const handleEditPermissions = (userData, actionType) => {
    setEditRole(userData);
    setActionType(actionType);
    setPopupOpen(true);
  }

  return (
    <div className='mainContainer'>
      <div className="lowerTop d-flex">
        <div className="title-box">
          <h3>{props.secondaryTitle}</h3>
        </div>
        <div className="inputslowerTop">
          <Grid container spacing={3}>
            {isFullAccess && <Button className='btnstop' onClick={() => createRole() }><Add />Add Role</Button> }
            <ManageRolesPermissionsPopup
              open={popupOpen}
              onClose={handleClosePopup}
              onSave={handleSave}
              getRoleData={getRoleData}
              roleData={editRole}
              allModules={allModules}
              actionType={actionType}
              setActionType={(action) => setActionType(action)}
              editRoleData={editRole}
              getRoleTable={getRoleTable}
              allRoles={allRoles}
            /> 
          </Grid>
        </div>
      </div>
      <div className='commonTable'>
        <CommonTable
          component="ManageRoles"
          data={data}
          defaultSortColumn="ASC"
          getRoleTable={getRoleTable}
          columns={columns}
          filters={filter}
          onChange={getRoleTable}
          handleModifyPermissions={handleEditPermissions}
        />
        {loading && <Loader />}
      </div>
    </div>
  );
}

export default ManageRoles;

ManageRoles.propTypes = {
  secondaryTitle: PropTypes.string.isRequired,
};
