import React, { useEffect, useState, useRef, useCallback } from 'react';
import { Button, Grid  } from '@mui/material';
import { FilterAlt, Add } from '@mui/icons-material/';
import { toast } from 'react-toastify';
import { useOutletContext } from 'react-router-dom';
import PropTypes from "prop-types";
import CommonTable from '../components/CommonTable.js';
import PopupForm from '../components/PopupForm.js';
import PopupForFilter from '../components/PopupForFilter.js';
import { addUser, getAllUsers, getManageRole } from "../constants/apiEndPoints.js";
import useApiService from "../services/apiService.js";
import Loader from '../components/Loader.js';
import { UserStatus } from '../constants/userStatus.js';
import { useUser } from "../context/UserContext.js"
import { permissionTypes } from '../constants/userConstants.js';
import './ManageUsers.css';


function ManageUsers(props) {
  const { permissionId } = useOutletContext();
  const isFullAccess = permissionId === `${permissionTypes[0].key}`;
  const { user } = useUser()
  const [showPopup, setShowPopup] = useState(false);
  const [showPopupFilter, setShowPopupFilter] = useState(false);
  const { postApi } = useApiService();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState([])
  const [allRoles, setAllRoles] = useState([])
  const hasFetchedRef = useRef(false);
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    role: '',
    status: ''
  });

  const initialFilter = {
    "PageNumber": 1,
    "PageSize": 50,
    "Filter": {
      "SortColumn": null,
      "SortDirection": null,
      "FilterColumn": null,
      "FilterValue": null,
    },
    "selectedValues": {
      "active": false,
      "admin": false,
      "user": false,
      "manager": false,
      "deactive": false,
      "superAdmin": false,
      "deleted": false,
    }
  }
  const [filter, setFilter] = useState(initialFilter)

  const getUsersTable = useCallback(async (updatedFilter) => {
    setLoading(true);
    try {
      const currentFilter = filter;
      const updatedFilterData = { ...currentFilter, ...updatedFilter };
      setFilter(updatedFilterData);
      const result = await postApi(getAllUsers, updatedFilterData);
      setData(result || []);
    } catch (error) {
      console.error("Error fetching users:", error);
      toast.error("Failed to load users. Please try again.");
    } finally {
      setLoading(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [postApi, filter]);

  const fetchAllRoles = useCallback(async (payload) => {
    console.log('🔴 ManageUsers fetchAllRoles called:', { payload, timestamp: new Date().toISOString() });
    const data = await postApi(getManageRole, payload)
    if (data?.Records?.length > 0) {
      setAllRoles(data.Records || [])
    } else {
      toast.error('Something went wrong')
    }
  }, [postApi]);

  useEffect(() => {
    if (hasFetchedRef.current) return;
    hasFetchedRef.current = true;
    
    const userDetails = JSON.parse(localStorage.getItem('user'));
    getUsersTable({});
    const payload = { 
      Email: user?.user_email || userDetails.user_email,
      SortType: "ASC",
      RoleId: null,
      PageNumber: 1,
      PageSize: 50,
      SortColumn: "Role_Name",
      Status: true,
    }
    fetchAllRoles(payload)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // Only run once on mount - ref guard ensures no duplicates


  const columns = [
    { field: 'user_first_name', headerName: 'First Name', type: String, flex: 2 },
    { field: 'user_last_name', headerName: 'Last Name', type: String, flex: 2 },
    { field: "user_email", headerName: 'Email', type: String, flex: 3 },
    { field: 'user_role_name', headerName: 'Role', type: String, flex: 1 },
    { field: 'user_status_name', headerName: 'Status', type: String, flex: 1 },
    { field: 'Action', headerName: 'Action', type: Element , sortable: false, flex: 1, disableColumnSelector: !isFullAccess },
  ];

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value
    })
  };

  const resetFormData = () => {
    setFormData({
      firstName: '',
      lastName: '',
      email: '',
      role: '', 
      status: ''
    })
    setErrors({});
  }

  const togglePopup = () => {
    setShowPopup(!showPopup);
  };


  const togglePopupFilter = () => {
    setShowPopupFilter(!showPopupFilter);
  };

  const handleClosePopup = () => {
    setShowPopup(false);
    resetFormData();
  };

  const handleClosePopupFilter = () => {
    setShowPopupFilter(false);
  };

 const onSubmit = async () => {
  const formErrors = validate();
  setErrors(formErrors);
  if (Object.keys(formErrors)?.length !== 0) {
    return;
  }

  const role_id = allRoles.find(role => role.Role_Id === formData.role)?.Role_Id;

  const filter = {
    UserId: 0,
    UserFirstName: formData.firstName,
    UserLastName: formData.lastName,
    UserEmail: formData.email,
    UserStatus: `${UserStatus.Active}`,
    UserRoleId: role_id,
    IsActive: true,
    IsDeleted: false,
  };

  setLoading(true);
  try {
    const result = await postApi(addUser, filter, true);
    if (result?.IsSuccess) {
      toast.success("User added successfully!");
    } else {
      toast.error(result?.Message || "Failed to add user");
      setResults(result?.Message || "Unknown error");
    }

    // Update table after adding user
    try {
      await getUsersTable(filter);
    } catch (tableError) {
      console.error("Error updating users table:", tableError);
      toast.error("Failed to refresh users table");
    }
  } catch (error) {
    console.error("Error adding user:", error);
    toast.error(error?.message || "Something went wrong while adding user");
  } finally {
    setLoading(false);
    handleClosePopup();
    setFormData({
      firstName: '',
      lastName: '',
      email: '',
      role: '',
      status: '',
    });
  }
};

 
  const [errors, setErrors] = useState({});

 const validate = () => {
  const formErrors = {};

  if (formData.firstName.trim() === "") {
    formErrors.firstName = "Name is required";
  }

  if (formData.lastName?.trim() === "") {
    formErrors.lastName = "Name is required";
  }

  if (formData.email === "") {
    formErrors.email = "Email is required";
  } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
    formErrors.email = "Email address is invalid";
  } else if (
    user?.whitelistdomain &&
    !user.whitelistdomain
      .split(",")
      .some((domain) =>
        formData.email.toLowerCase().endsWith(`@${domain.trim().toLowerCase()}`)
      )
  ) {
    formErrors.email = "Email address is not allowed";
  }

  if (formData.role === "") {
    formErrors.role = "Role is required";
  }

  return formErrors;
};




  const handleUpdateFilter = (updatedFilter, isClear) => { 
    if(!updatedFilter.Filter?.FilterValue?.length || !updatedFilter.Filter?.FilterColumn?.length) {
      setFilter(initialFilter)
    }
    else {
      setFilter(isClear ? initialFilter : updatedFilter)
    }
  }

  return (
    <div className='mainContainer manager-users'>
      <div className="lowerTop d-flex">
        <div className="title-box">
          <h3>{props?.secondaryTitle}</h3>
        </div>
        <div className="inputslowerTop rightActButtons">
          <Grid container spacing={3}>
            {isFullAccess && <Button className='btnstop' onClick={togglePopup}><Add />Add Users</Button>}
            {showPopup && (
              <dialog className="popup" open aria-labelledby="add-user-title">
                <PopupForm
                  data={results}
                  handleInputChange={handleInputChange}
                  formData={formData}
                  setFormData={setFormData}
                  onClose={handleClosePopup}
                  onSubmit={onSubmit}
                  errors={errors}
                  setErrors={setErrors}
                  allRoles={allRoles}
                  user={user}
                />
              </dialog>
            )}
            <Button className='btnstop' onClick={togglePopupFilter}><FilterAlt />Filter</Button>
          </Grid>
          {showPopupFilter && (
            <dialog className="popup" open aria-labelledby="filter-title">
              <PopupForFilter onClose={handleClosePopupFilter} getUsersTable={getUsersTable} filter={filter} handleFilter={handleUpdateFilter} allRoles={allRoles} />
            </dialog>
          )}
        </div>
      </div>
      <div className='commonTable'>
        <CommonTable component="ManageUser" data={data} defaultSortColumn="ASC" getUsersTable={getUsersTable} columns={columns} filters={filter} onChange={getUsersTable} />
        {loading && <Loader />}
      </div>
    </div>
  );
}
ManageUsers.propTypes = {
  secondaryTitle: PropTypes.string, 
};

export default ManageUsers;
