import React, { useEffect, useRef, useState, useMemo } from "react";
import { Spinner } from "react-bootstrap";
import config from "../../config/config";
import { apiCall } from "../../_services/apiCall";
import { sweetAlert } from "../../utils/UniversalFunction";
import Loader from "../loader/Loader";
import PhoneInput from "react-phone-input-2";
import "react-phone-input-2/lib/style.css";
import ReAssignQuestions from "../Company Sub Admin/Component/Sector Questions/ReassignUser";
import { Modal, ModalHeader } from "../../globalComponents/ui/Modal";
import { PrimaryButton, SecondaryButton, DangerButton } from "../../globalComponents/ui/Button";
import MultiSelectDropdown from "../../globalComponents/form/dropdowns/MultiSelectDropdown";
import { usePermission } from "../../hooks/usePermission";
import {
  SettingLayout,
  SettingsFilterCard, SettingsSearchWrap,
  SettingsCard, SettingsSectionHeader, SettingsSectionTitle, SettingsCountChip,
  SettingsActionBtn,
  SettingsStatusBadge,
  SettingsModalBody, SettingsModalFooter,
  SettingsFormGroup, SettingsFormLabel, SettingsFormInput,
  SettingsFormSelect, SettingsFormGrid,
  SettingsWarningBlock,
} from "./SettingShell";
import DataTable from "../../globalComponents/ui/DataTable/DataTable";
import styled from "styled-components";

const LocationRow = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 14px;
  border-bottom: 1px solid #f1f5f9;
  font-size: 13px;
  color: #1e293b;
  &:last-child { border-bottom: none; }
`;

const LocationRowIndex = styled.span`
  color: #94a3b8;
  font-size: 11px;
  min-width: 20px;
  flex-shrink: 0;
`;

const ClickableStatusBadge = styled(SettingsStatusBadge)`
  cursor: pointer;
  transition: all 0.2s ease-in-out;
  user-select: none;
  
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.08), 0 2px 4px -1px rgba(0, 0, 0, 0.04);
    opacity: 0.95;
    border-color: ${({ $active }) => ($active ? "#22c55e" : "#ef4444")};
  }
  
  &:active {
    transform: translateY(0);
    box-shadow: none;
  }
`;

const UserDetailField = styled.div`
  display: flex;
  flex-direction: column;
  gap: 4px;
`;

const UserDetailLabel = styled.span`
  font-size: 10px;
  font-weight: 700;
  color: #64748b;
  text-transform: uppercase;
  letter-spacing: 0.4px;
`;

const UserDetailValue = styled.div`
  padding: 8px 12px;
  border: 1.5px solid #e2e8f0;
  border-radius: 9px;
  font-size: 13px;
  color: #1e293b;
  background: #f8fafc;
  min-height: 38px;
  display: flex;
  align-items: center;
  gap: 8px;
`;



const companyOptions = [
  { label: "Kennametal India Limited (KIL)", value: "Kennametal India Limited (KIL)" },
  { label: "Kennametal Shared Services Private Limited (KSSPL)", value: "Kennametal Shared Services Private Limited (KSSPL)" },
];

const AudienceOptions = [
  { label: "Permanent Employee", value: "EMPLOYEES_PERMANENT" },
  { label: "Other than Permanent Employee", value: "EMPLOYEES_TEMPORARY" },
  { label: "Permanent Worker", value: "WORKERS_PERMANENT" },
  { label: "Other than Permanent Worker", value: "WORKERS_TEMPORARY" },
  { label: "KMP", value: "KMP" },
  { label: "BOD", value: "BOD" },
  { label: "Customer", value: "CUSTOMERS" },
  { label: "Supplier", value: "SUPPLIERS" },
  { label: "Distributor", value: "DISTRIBUTORS" },
];

const businessUnitOptions = [
  { label: "Metal Cutting Demand Fulfillment", value: "Metal Cutting Demand Fulfillment" },
  { label: "Metal Cutting Demand Generation", value: "Metal Cutting Demand Generation" },
  { label: "Infrastructure Business Group", value: "Infrastructure Business Group" },
  { label: "Administration Office", value: "Administration Office" },
  { label: "Finance", value: "Finance" },
  { label: "Technology", value: "Technology" },
  { label: "Office of General Counsel", value: "Office of General Counsel" },
  { label: "Global Sourcing & Procurement", value: "Global Sourcing & Procurement" },
];

const divisionOptions = [
  { label: "Advanced Material Solutions", value: "Advanced Material Solutions" },
  { label: "Business Finance", value: "Business Finance" },
  { label: "Commercial Field", value: "Commercial Field" },
  { label: "Corporate Finance", value: "Corporate Finance" },
  { label: "Earthcutting", value: "Earthcutting" },
  { label: "Engineered Components", value: "Engineered Components" },
  { label: "Environmental Health and Safety", value: "Environmental Health and Safety" },
  { label: "General", value: "General" },
  { label: "General Counsel", value: "General Counsel" },
  { label: "HR Business Partners", value: "HR Business Partners" },
  { label: "Inserts", value: "Inserts" },
  { label: "Machining Solutions Group", value: "Machining Solutions Group" },
  { label: "Materials Science", value: "Materials Science" },
  { label: "Portfolio Management", value: "Portfolio Management" },
  { label: "Procurement", value: "Procurement" },
  { label: "Product Engineering", value: "Product Engineering" },
  { label: "Quality", value: "Quality" },
  { label: "Strategic Marketing", value: "Strategic Marketing" },
  { label: "Supply Planning & Logistics", value: "Supply Planning & Logistics" },
  { label: "Technology Industrial", value: "Technology Industrial" },
];

const departmentOptions = [
  { label: "MCDG - Sales", value: "MCDG - Sales" },
  { label: "MCDF + Infra Mfg - Manufacturing", value: "MCDF + Infra Mfg - Manufacturing" },
  { label: "MSG", value: "MSG" },
  { label: "Infrastructure", value: "Infrastructure" },
  { label: "Marketing", value: "Marketing" },
  { label: "Finance", value: "Finance" },
  { label: "HR", value: "HR" },
  { label: "Legal", value: "Legal" },
  { label: "R&D", value: "R&D" },
  { label: "Sourcing", value: "Sourcing" },
  { label: "EHS", value: "EHS" },
  { label: "Supply Chain & Distribution", value: "Supply Chain & Distribution" },
  { label: "ESG", value: "ESG" },
  { label: "Technology", value: "Technology" },
  { label: "Admin", value: "Admin" },
  { label: "MCDF", value: "MCDF" },
  { label: "Manufacturing", value: "Manufacturing" },
  { label: "Design", value: "Design" },
  { label: "Supply Planning & Logistics", value: "Supply Planning & Logistics" },
  { label: "Customer Service", value: "Customer Service" },
  { label: "Application Engineering", value: "Application Engineering" },
  { label: "Performance Value", value: "Performance Value" },
  { label: "Field", value: "Field" },
  { label: "Business Partners", value: "Business Partners" },
  { label: "Health and Safety", value: "Health and Safety" },
  { label: "Product Engineering", value: "Product Engineering" },
  { label: "Sales", value: "Sales" },
  { label: "Business Finance", value: "Business Finance" },
  { label: "Business Services", value: "Business Services" },
  { label: "Technology Industrial", value: "Technology Industrial" },
  { label: "Materials Science", value: "Materials Science" },
  { label: "Quality", value: "Quality" },
  { label: "Tax", value: "Tax" },
  { label: "General Counsel", value: "General Counsel" },
  { label: "End Market Strategies", value: "End Market Strategies" },
  { label: "Procurement", value: "Procurement" },
  { label: "General Mgmt/Admin", value: "General Mgmt/Admin" },
  { label: "Product Management Operations", value: "Product Management Operations" },
  { label: "Machine Tool Industry", value: "Machine Tool Industry" },
];

/**
 * Stable key for one reportable scope — a whole location, or a single
 * sub-location within it. Used as the picker's option value and to match a
 * user's existing assignments, which are location+sub-location pairs.
 */
const scopeKey = (locationId, subLocationId) =>
  `${locationId}:${subLocationId ?? ""}`;

/** Splits a scope key back into the ids the assignment API expects. */
const parseScopeKey = (key) => {
  const [locationId, subLocationId] = String(key).split(":");
  return {
    locationId: Number(locationId),
    subLocationId: subLocationId ? Number(subLocationId) : null,
  };
};

/** Human-readable address for a location row from getSource's `data` array. */
const buildLocationAddress = (item) => {
  const isHQ = item.headOffice === true || item.head_Office === true;
  const parts = [
    item.location?.area,
    item.location?.city,
    item.location?.state,
    item.location?.country,
    item.location?.zipCode,
  ].filter(Boolean);
  if (parts.length > 0) return parts.join(", ");
  return isHQ ? "Corporate Headquarters" : `Location ${item.id}`;
};

/** Maps getSource's `locationOptions` onto their parent location's address. */
const decorateLocationOptions = (payload) => {
  const addressByLocationId = new Map(
    (payload?.data || []).map((item) => [Number(item.id), buildLocationAddress(item)]),
  );
  return (payload?.locationOptions || []).map((opt) => ({
    ...opt,
    address: addressByLocationId.get(Number(opt.locationId)) || "",
  }));
};

// ─── Component ────────────────────────────────────────────────────────────────

const SubUsers = ({ userPermissionList }) => {
  const [updateLoader, setUpdateLoader] = useState(false);
  const [source_ids, setSource_ids] = useState([]);
  const [submitted, setSubmitted] = useState(false);
  const [useLoader, setUseLoader] = useState(false);
  const [roleIds, setRoleIds] = useState([]);
  const [roleId, setRoleId] = useState(null);
  const [newRoleName, setNewRoleName] = useState("");
  const [designationId, setDesignationId] = useState(null);
  const [showSkelton, setshowSkelton] = useState(false);
  const [userList, setUserList] = useState(null);
  const [joiningDate, setJoiningDate] = useState("");
  const [userDetails, setUserDetails] = useState({ firstName: "", lastName: "", emailId: "", employeeId: "" });
  const [selectedRow, setSelectedRow] = useState(null);
  const [usersId, setUsersId] = useState();
  const [removeUserLocationId, setRemoveUserLocationId] = useState();
  const [removeSubLocationId, setRemoveSubLocationId] = useState(null);
  const [addNewUserPopup, setAddNewUserPopup] = useState(false);
  const [addNewLocationPopup, setAddNewLOcationPopup] = useState(false);
  const [designationList, setDesignationList] = useState(null);
  const [locationUsedIds, setLocationUsedIds] = useState([]);
  const [roleList, setRoleList] = useState();
  const [onlyAuditor, setOnlyAuditor] = useState(false);
  const [headOfficeTrue, setHeadOfficeTrue] = useState([]);
  const [headOfficeFalse, setHeadOfficeFalse] = useState([]);
  const [enable, setEnable] = useState();
  const [businessUnit, setBusinessUnit] = useState("");
  const [division, setDivision] = useState("");
  const [departmentId, setDepartmentId] = useState("");
  const [currentId, setCurrentId] = useState(null);
  const [showModal, setShowModal] = useState(false);

  const [convertPopup, setConvertPopup] = useState(false);
  const [convertTrainees, setConvertTrainees] = useState([]);
  const [convertUserIds, setConvertUserIds] = useState([]);
  const [convertRoleIds, setConvertRoleIds] = useState([]);
  const [convertLoader, setConvertLoader] = useState(false);
  const [convertListLoading, setConvertListLoading] = useState(false);
  const [convertListError, setConvertListError] = useState(false);
  const [convertSubmitted, setConvertSubmitted] = useState(false);

  // Edit User details state hooks
  const [editUserPopup, setEditUserPopup] = useState(false);
  const [editUserId, setEditUserId] = useState(null);
  const [editUserDetails, setEditUserDetails] = useState({ firstName: "", lastName: "", emailId: "", employeeId: "" });
  const [editRoleIds, setEditRoleIds] = useState([]);
  const [editRoleId, setEditRoleId] = useState(null);
  const [editNewRoleName, setEditNewRoleName] = useState("");
  const [editDesignationId, setEditDesignationId] = useState(null);
  const [editPhone, setEditPhone] = useState("");
  const [editJoiningDate, setEditJoiningDate] = useState("");
  const [editGender, setEditGender] = useState("");
  const [editCategoryId, setEditCategoryId] = useState("");
  const [editCompanyName, setEditCompanyName] = useState("");
  const [editBusinessUnit, setEditBusinessUnit] = useState("");
  const [editDivision, setEditDivision] = useState("");
  const [editDepartmentId, setEditDepartmentId] = useState("");
  const [locationSearchQuery, setLocationSearchQuery] = useState("");

  // Click-outside listener for custom select dropdown is obsolete as MultiSelectDropdown manages its own refs.
  const [gender, setGender] = useState("");
  const [categoryId, setCategoryId] = useState("");
  const [companyName, setCompanyName] = useState("");
  const [activebtnTab, setactivebtnTab] = useState(0);
  const [deleteModal, setDeleteModal] = useState(false);
  const [reassignShow, setReassignShow] = useState(false);
  const [locationList, setLocationList] = useState([]);

  // Options come from getSource's `locationOptions`, which lists one entry per
  // reportable scope: a whole location (BLR) or a single sub-location (KMC-T1).
  // A site that has sub-locations is only offered as its sub-locations.
  const mappedLocationOptions = useMemo(() => {
    return (locationList || []).map(opt => ({
      value: scopeKey(opt.locationId, opt.subLocationId),
      label: opt.address ? `${opt.displayName} - ${opt.address}` : opt.displayName,
    }));
  }, [locationList]);

  const mappedRoleOptions = useMemo(() => {
    return (roleList || []).map(r => ({
      value: r.id,
      label: r.role_name,
    }));
  }, [roleList]);

  const convertUserOptions = useMemo(() => {
    return (convertTrainees || []).map(t => {
      const name = `${t.first_name || ""} ${t.last_name || ""}`.trim() || "Unnamed user";
      return {
        value: t.id,
        label: t.email ? `${name} (${t.email})` : name,
      };
    });
  }, [convertTrainees]);

  useEffect(() => {
    setRoleId(roleIds[0] || null);
  }, [roleIds]);

  useEffect(() => {
    setEditRoleId(editRoleIds[0] || null);
  }, [editRoleIds]);

  const [phone, setPhone] = useState("");
  const [filterListValue, setFilterListValue] = useState();
  const [showModalUserDetail, setShowModalUserDetail] = useState(false);
  const [clickedRow, setClickedRow] = useState(null);
  const [companyId, setCompanyId] = useState();
  const isMounted = useRef(true);

  const userId = JSON.parse(localStorage.getItem("user_temp_id"));

  // ─── Permission helpers ──────────────────────────────────────────────────────
  const [canInvite] = usePermission("user-management.invite", "INVITE");
  const [canAddLoc] = usePermission("user-management.add-location", "ADDLOCATION");
  const [canEditLegacy] = usePermission("user-management.update", "EDIT");
  const [canEditUpdateSubUser] = usePermission("user-management.update", "UPDATE_SUB_USER");
  const canEdit = canEditLegacy || canEditUpdateSubUser || canInvite;

  // ─── Lifecycle ───────────────────────────────────────────────────────────────
  useEffect(() => {
    const currentUser = localStorage.getItem("tmpcurrentUser");
    if (currentUser) setCompanyId(String(JSON.parse(currentUser).data.user.dataValues.company_id));
    return () => { isMounted.current = false; };
  }, []);

  useEffect(() => { getSubUser(); getLocation(); }, []);

  useEffect(() => {
    if (userList?.length > 0) {
      selectRow(userList[0]);
    }
  }, [userList]);

  useEffect(() => {
    if (roleList?.length > 0 && roleIds.length > 0) {
      const hasAuditorRole = roleList.some(r => roleIds.includes(r.id) && r.onlyauditor);
      setOnlyAuditor(hasAuditorRole);
    } else {
      setOnlyAuditor(false);
    }
  }, [roleIds, roleList]);

  // ─── API calls (logic unchanged) ────────────────────────────────────────────
  const getSubUser = async () => {
    setshowSkelton(true);
    const { isSuccess, data } = await apiCall(`${config.POSTLOGIN_API_URL_COMPANY}getSubUser`, {}, { userId }, "GET");
    setshowSkelton(false);
    if (isSuccess) {
      const locationIds = await handleLocationId(data?.data);
      setLocationUsedIds(locationIds);
      setUserList(data?.data?.reverse());
      setFilterListValue(data?.data?.reverse());
    }
  };

  const handleResendCredentials = async (uid) => {
    await apiCall(`${config.POSTLOGIN_API_URL_COMPANY}reSendCredicial`, {}, { userId: uid }, "POST");
  };

  const getLocationById = async (assignedScopeKeys) => {
    const { isSuccess, data } = await apiCall(`${config.POSTLOGIN_API_URL_COMPANY}getSource`, {}, { userId }, "GET");
    if (isSuccess) {
      const assigned = new Set(assignedScopeKeys || []);
      setLocationList(
        decorateLocationOptions(data).filter(
          opt => !assigned.has(scopeKey(opt.locationId, opt.subLocationId)),
        ),
      );
    }
  };

  const getLocation = async () => {
    const { isSuccess, data } = await apiCall(`${config.POSTLOGIN_API_URL_COMPANY}getSource`, {}, { userId }, "GET");
    if (isSuccess) setLocationList(decorateLocationOptions(data));
  };

  const getRoleById = async () => {
    const { isSuccess, data } = await apiCall(`${config.POSTLOGIN_API_URL_COMPANY}authorization/roles`, {}, {}, "GET");
    if (isSuccess) {
      const rawRoles = Array.isArray(data) ? data : (data?.data || []);
      const mappedRoles = rawRoles.map(r => ({
        ...r,
        role_name: r.displayName || r.name,
      }));
      setRoleList(mappedRoles);
    }
  };

  const getDesignationById = async () => {
    const { isSuccess, data } = await apiCall(`${config.POSTLOGIN_API_URL_COMPANY}getDesignation`, {}, { userId }, "GET");
    if (isSuccess) {
      const list = data?.data?.reverse();
      setDesignationList(list);
      if (list && list.length > 0) {
        setDesignationId(list[0].id);
      }
    }
  };

  const sendInvite = async () => {
    setUpdateLoader(true);
    const { isSuccess } = await apiCall(
      `${config.POSTLOGIN_API_URL_COMPANY}inviteSubUser`, {},
      {
        firstName: userDetails?.firstName, lastName: userDetails?.lastName,
        emailId: userDetails?.emailId, gender, categoryId, companyName,
        employeeId: userDetails?.employeeId, mobileNumber: phone,
        invitedBy: Number(userId), designationId: Number(designationId),
        roleId: roleId ? Number(roleId) : null,
        roleIds: roleIds.map(Number),
        newRoleName: newRoleName || null,
        businessUnit, division, departmentId, joiningDate: joiningDate || null,
      }, "POST"
    );
    setUpdateLoader(false);
    if (isSuccess) {
      getSubUser();
      setAddNewUserPopup(false);
      setPhone("");
      setJoiningDate("");
      setNewRoleName("");
      setUserDetails({ firstName: "", lastName: "", emailId: "", employeeId: "" });
    }
  };

  const getConvertibleTrainees = async () => {
    setConvertListLoading(true);
    setConvertListError(false);
    const { isSuccess, data } = await apiCall(`${config.POSTLOGIN_API_URL_COMPANY}getConvertibleTrainees`, {}, {}, "GET");
    setConvertListLoading(false);
    if (isSuccess) {
      setConvertTrainees(data?.data || []);
    } else {
      setConvertTrainees([]);
      setConvertListError(true);
    }
  };

  const convertTraineeToEmployee = async () => {
    setConvertSubmitted(true);
    if (convertUserIds.length === 0 || convertRoleIds.length === 0) return;
    setConvertLoader(true);
    const { isSuccess, data } = await apiCall(
      `${config.POSTLOGIN_API_URL_COMPANY}convertTraineeToEmployee`, {},
      { userIds: convertUserIds.map(Number), roleIds: convertRoleIds.map(Number) }, "POST",
      true, false
    );
    setConvertLoader(false);
    if (isSuccess) {
      const convertedCount = data?.data?.converted?.length ?? 0;
      const skippedCount = data?.data?.skipped?.length ?? 0;
      const summary = skippedCount > 0
        ? `${convertedCount} converted, ${skippedCount} skipped`
        : `${convertedCount} converted`;
      sweetAlert(skippedCount > 0 ? "warning" : "success", summary);
      handleCloseConvertPopup();
      getSubUser();
    }
  };

  const addLocation = async () => {
    setUpdateLoader(true);

    // The picker selects scopes; the API takes locations and sub-locations
    // separately. A sub-location pick still carries its parent location.
    const locationIds = new Set();
    const subLocationIds = new Set();
    source_ids.forEach(key => {
      const { locationId, subLocationId } = parseScopeKey(key);
      locationIds.add(locationId);
      if (subLocationId) subLocationIds.add(subLocationId);
    });

    const { isSuccess } = await apiCall(
      `${config.POSTLOGIN_API_URL_COMPANY}addLocationToUser`, {},
      {
        sourceId: JSON.stringify(Array.from(locationIds)),
        subLocationIds: JSON.stringify(Array.from(subLocationIds)),
        userId: usersId,
      }, "POST"
    );
    setUpdateLoader(false);
    if (isSuccess) { handleCloseLocationPopup(); getSubUser(); }
  };

  const actionUser = async () => {
    const { isSuccess } = await apiCall(
      `${config.POSTLOGIN_API_URL_COMPANY}actionOnSubUser`, {},
      { userId: currentId, status: enable }, "POST"
    );
    if (isSuccess) { getSubUser(); setCurrentId(null); setShowModal(false); }
  };

  const handleToggleTwoFactor = async (email, employeeId, status) => {
    const { isSuccess } = await apiCall(
      `${config.POSTLOGIN_API_URL_COMPANY}handleToggleTwoFactor`, {},
      { email, employeeId, status }, "POST"
    );
    if (isSuccess) getSubUser();
  };

  const deleteLocation = async () => {
    // Removing a sub-location leaves the parent location assigned, so the
    // sub-location id has to be sent alongside it rather than instead of it.
    const { isSuccess } = await apiCall(
      `${config.POSTLOGIN_API_URL_COMPANY}removeLocation`, {},
      {
        userId: removeUserLocationId,
        locationId: currentId,
        ...(removeSubLocationId ? { subLocationId: removeSubLocationId } : {}),
      }, "POST"
    );
    if (isSuccess) {
      getSubUser();
      setCurrentId(null);
      setRemoveSubLocationId(null);
      setDeleteModal(false);
    }
  };

  // ─── Helpers ─────────────────────────────────────────────────────────────────
  const handleLocationId = async (inputData) => {
    const ids = [];
    (inputData || []).forEach(item => {
      (item.location || []).forEach(loc => {
        if (loc.sourceId !== undefined) ids.push(scopeKey(loc.sourceId, loc.subLocationId));
      });
    });
    return ids;
  };

  const selectRow = (userData) => {
    setSelectedRow(userData);
    setRemoveUserLocationId(userData?.userId);
    setHeadOfficeTrue(userData.location.filter(l => l.headOffice === true));
    setHeadOfficeFalse(userData.location.filter(l => l.headOffice === false));
  };

  const handleSearch = (term) => {
    const q = term.trim().toLowerCase();
    if (!q) { setFilterListValue([...userList]); return; }
    setFilterListValue(userList.filter(item => item.firstName.toLowerCase().includes(q)));
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setUserDetails(prev => ({ ...prev, [name]: value }));
  };

  const handleToggle = (id, status) => { setEnable(!status); setShowModal(true); setCurrentId(id); };
  const removeLocation = (id, subLocationId = null) => {
    setDeleteModal(true);
    setCurrentId(id);
    setRemoveSubLocationId(subLocationId);
  };

  const handleShowNewUserPopup = () => { setAddNewUserPopup(true); getRoleById(); getDesignationById(); };
  const handleCloseNewUserPopup = () => { setRoleId(null); setRoleIds([]); setAddNewUserPopup(false); };

  /**
   * Updates the selected trainees without touching the role selection, so
   * hand-picked roles survive adding/removing trainees. Roles are reset only
   * when the popup opens/closes (handleShowConvertPopup /
   * handleCloseConvertPopup), and whatever roles are picked are applied
   * uniformly to every selected trainee by convertTraineeToEmployee.
   */
  const handleConvertUsersChange = (ids) => {
    setConvertUserIds(ids);
  };

  const handleShowConvertPopup = () => {
    setConvertPopup(true);
    setConvertUserIds([]);
    setConvertRoleIds([]);
    setConvertSubmitted(false);
    getConvertibleTrainees();
    getRoleById();
  };
  const handleCloseConvertPopup = () => {
    setConvertPopup(false);
    setConvertUserIds([]);
    setConvertRoleIds([]);
    setConvertSubmitted(false);
  };

  const handleShowEditUserPopup = async (userData) => {
    setEditUserId(userData.userId);
    setEditUserDetails({
      firstName: userData.firstName || "",
      lastName: userData.lastName || "",
      emailId: userData.emailId || "",
      employeeId: userData.employeeId || ""
    });
    setEditRoleIds(userData.roleIds || (userData.roleId ? [Number(userData.roleId)] : []));
    setEditRoleId(userData.roleId || null);
    setEditNewRoleName("");
    setEditDesignationId(userData.designationId || null);
    setEditPhone(userData.mobileNumber || "");
    setEditJoiningDate(userData.joiningDate ? userData.joiningDate.split("T")[0] : "");
    setEditGender(userData.gender || "");
    setEditCategoryId(userData.categoryId || "");
    setEditCompanyName(userData.companyName || "");
    setEditBusinessUnit(userData.businessUnit || "");
    setEditDivision(userData.division || "");
    setEditDepartmentId(userData.departmentId || "");
    setSubmitted(false);
    setEditUserPopup(true);
    await getRoleById();
    await getDesignationById();
  };

  const updateSubUser = async () => {
    setSubmitted(true);
    if (!editUserDetails?.firstName || !editUserDetails?.emailId || (editRoleIds.length === 0 && !editNewRoleName)) {
      return;
    }
    setUpdateLoader(true);
    const { isSuccess } = await apiCall(
      `${config.POSTLOGIN_API_URL_COMPANY}updateSubUser`, {},
      {
        userId: Number(editUserId),
        firstName: editUserDetails?.firstName,
        lastName: editUserDetails?.lastName,
        emailId: editUserDetails?.emailId,
        employeeId: editUserDetails?.employeeId,
        mobileNumber: editPhone,
        gender: editGender,
        categoryId: editCategoryId,
        companyName: editCompanyName,
        designationId: editDesignationId ? Number(editDesignationId) : null,
        roleId: editRoleId ? Number(editRoleId) : null,
        roleIds: editRoleIds.map(Number),
        newRoleName: editNewRoleName || null,
        businessUnit: editBusinessUnit,
        division: editDivision,
        departmentId: editDepartmentId,
        joiningDate: editJoiningDate || null,
      }, "POST"
    );
    setUpdateLoader(false);
    if (isSuccess) {
      getSubUser();
      setEditUserPopup(false);
    }
  };
  const handleCloseLocationPopup = () => {
    setAddNewLOcationPopup(false);
    setSource_ids([]);
  };

  const handleShowNewLocationPopup = (id, location) => {
    setAddNewLOcationPopup(true);
    setUsersId(id);
    setSource_ids([]);
    // Match on location+sub-location: a user holding KMC-T1 must still be
    // offered KMC-T2.
    const assignedScopeKeys = (location || []).map(obj => scopeKey(obj.sourceId, obj.subLocationId));
    getLocationById(assignedScopeKeys);
  };

  const handleImageClick = (data, rowIndex) => {
    setShowModalUserDetail(true);
    setClickedRow(clickedRow === rowIndex ? null : rowIndex);
    selectRow(data);
    setLocationSearchQuery("");
  };

  const renderLocationTab = () => {
    const allLocations = selectedRow?.location || [];
    const query = (locationSearchQuery || "").trim().toLowerCase();

    const filteredLocations = allLocations.filter(loc => {
      if (!query) return true;
      const text = `${loc?.location?.area || ""} ${loc?.location?.city || ""} ${loc?.location?.state || ""} ${loc?.location?.country || ""} ${loc?.location?.zipCode || ""} ${loc?.unitCode || ""}`.toLowerCase();
      return text.includes(query);
    });

    if (!allLocations.length) {
      return (
        <div style={{ padding: "16px", fontSize: 12, color: "#94a3b8", textAlign: "center" }}>
          No assigned locations.
        </div>
      );
    }

    if (!filteredLocations.length) {
      return (
        <div style={{ padding: "16px", fontSize: 12, color: "#94a3b8", textAlign: "center" }}>
          No matching locations found.
        </div>
      );
    }

    return filteredLocations.map((loc, i) => {
      const isHQ = loc.headOffice === true || loc.head_Office === true;
      const parts = [
        loc?.location?.area,
        loc?.location?.city,
        loc?.location?.state,
        loc?.location?.country,
        loc?.location?.zipCode
      ].filter(Boolean);
      const addressStr = parts.length > 0 ? parts.join(", ") : (isHQ ? "Corporate Headquarters" : `Location ${loc?.sourceId}`);

      return (
        <LocationRow key={i}>
          <i className={isHQ ? "fas fa-building" : "fas fa-map-marker-alt"} style={{ fontSize: 11, color: isHQ ? "#3f88a5" : "#64748b", flexShrink: 0 }} />
          <span style={{ flex: 1, fontSize: "12.5px", color: "#334155" }}>
            {loc?.unitCode ? <strong style={{ marginRight: "6px", color: "#1e293b" }}>[{loc.unitCode}]</strong> : null}
            {addressStr}
          </span>
          <SettingsActionBtn
            $variant="del"
            onClick={() => removeLocation(loc?.sourceId, loc?.subLocationId)}
            title={loc?.subLocationId ? "Remove sub-location" : "Remove location"}
          >
            <i className="fas fa-trash" />
          </SettingsActionBtn>
        </LocationRow>
      );
    });
  };

  const totalUsers = filterListValue?.length ?? 0;

  // ─── Render ───────────────────────────────────────────────────────────────────
  return (
    <SettingLayout
      title="User Management"
      subtitle={`${totalUsers} user${totalUsers !== 1 ? "s" : ""}`}
      $wide
      rightContent={
        canInvite && (
          <div style={{ display: "flex", gap: 10 }}>
            <SecondaryButton onClick={handleShowConvertPopup}>
              <i className="fas fa-user-check" aria-hidden="true" />
              Convert to Employee
            </SecondaryButton>
            <PrimaryButton onClick={handleShowNewUserPopup}>
              <i className="fas fa-user-plus" aria-hidden="true" />
              Add User
            </PrimaryButton>
          </div>
        )
      }
    >
      {/* Search */}
      <SettingsFilterCard>
        <SettingsSearchWrap>
          <i className="fas fa-search s-icon" aria-hidden="true" />
          <input
            type="search"
            placeholder="Search by first name…"
            onChange={e => handleSearch(e.target.value)}
          />
        </SettingsSearchWrap>
      </SettingsFilterCard>

      {/* User table */}
      <SettingsCard>
        <SettingsSectionHeader>
          <i className="fas fa-users" style={{ fontSize: 12, color: "#3f88a5" }} aria-hidden="true" />
          <SettingsSectionTitle>All users</SettingsSectionTitle>
          <SettingsCountChip>{totalUsers}</SettingsCountChip>
        </SettingsSectionHeader>

        {showSkelton ? (
          <div style={{ padding: 40 }}><Loader /></div>
        ) : (
          <DataTable
            title=""
            searchable={false}
            showPagination={filterListValue?.length > 20}
            columns={[
              { key: "firstName", label: "First Name", sortable: true },
              { key: "lastName", label: "Last Name", sortable: true },
              {
                key: "status",
                label: "Status",
                renderCell: (value, row) => (
                  <ClickableStatusBadge
                    $active={value === 1}
                    onClick={() => handleToggle(row._raw.userId, value)}
                    title="Click to toggle status"
                  >
                    {value ? "Active" : "Inactive"}
                  </ClickableStatusBadge>
                ),
              },
              {
                key: "twoFaStatus",
                label: "2FA",
                renderCell: (value) => (
                  <SettingsStatusBadge $active={value}>{value ? "On" : "Off"}</SettingsStatusBadge>
                ),
              },
            ]}
            data={(filterListValue || []).map(data => ({
              _id: data.userId,
              firstName: data.firstName,
              lastName: data.lastName,
              status: data.status,
              twoFaStatus: data.twoFaStatus,
              _raw: data,
            }))}
            emptyMessage="No users found. Invite your first user to get started."
            extraActions={(row) => [
              ...(canEdit ? [{ label: "Edit details", icon: "fas fa-edit", variant: "edit", onClick: () => handleShowEditUserPopup(row._raw) }] : []),
              { label: "Resend credentials", icon: "fas fa-envelope", variant: "view", onClick: () => handleResendCredentials(row._raw.userId) },
              { label: row._raw.twoFaStatus ? "Disable 2FA" : "Enable 2FA", icon: `fas fa-${row._raw.twoFaStatus ? "lock" : "unlock"}`, variant: "view", onClick: () => handleToggleTwoFactor(row._raw.emailId, row._raw.employeeId, !row._raw.twoFaStatus) },
              ...(canAddLoc ? [{ label: "Add location", icon: "fas fa-map-marker-alt", variant: "edit", onClick: () => handleShowNewLocationPopup(row._raw.userId, row._raw.location) }] : []),
              { label: "View details", icon: "fas fa-eye", variant: "view", onClick: () => handleImageClick(row._raw, row._raw.userId) },
            ]}
          />
        )}
      </SettingsCard>

      {/* ── Reassign questions ─────────────────────────────────────────────── */}
      {reassignShow && (
        <ReAssignQuestions
          usersId={usersId}
          financialYearId={6}
          reassignShow={reassignShow}
          onHide={() => setReassignShow(false)}
          type="USERID"
        />
      )}

      {/* ── User detail modal ──────────────────────────────────────────────── */}
      {clickedRow !== null && (
        <Modal
          show={showModalUserDetail}
          onClose={() => setShowModalUserDetail(false)}
          maxWidth={540}
        >
          <ModalHeader
            icon="fas fa-user"
            title="User Details"
            subtitle={`${selectedRow?.firstName || ""} ${selectedRow?.lastName || ""}`}
            onClose={() => setShowModalUserDetail(false)}
          />
          <SettingsModalBody>
            <SettingsFormGrid>
              <UserDetailField>
                <UserDetailLabel>First Name</UserDetailLabel>
                <UserDetailValue>{selectedRow?.firstName || "—"}</UserDetailValue>
              </UserDetailField>
              <UserDetailField>
                <UserDetailLabel>Last Name</UserDetailLabel>
                <UserDetailValue>{selectedRow?.lastName || "—"}</UserDetailValue>
              </UserDetailField>
            </SettingsFormGrid>

            <UserDetailField>
              <UserDetailLabel>Email Address</UserDetailLabel>
              <UserDetailValue>
                <i className="fas fa-envelope" style={{ fontSize: 11, color: "#3f88a5" }} />
                {selectedRow?.emailId || "—"}
              </UserDetailValue>
            </UserDetailField>

            <SettingsFormGrid>
              <UserDetailField>
                <UserDetailLabel>Employee ID</UserDetailLabel>
                <UserDetailValue>{selectedRow?.employeeId || "—"}</UserDetailValue>
              </UserDetailField>
              <UserDetailField>
                <UserDetailLabel>Mobile</UserDetailLabel>
                <UserDetailValue>{selectedRow?.mobileNumber || "—"}</UserDetailValue>
              </UserDetailField>
            </SettingsFormGrid>

            <SettingsFormGrid>
              <UserDetailField>
                <UserDetailLabel>Designation</UserDetailLabel>
                <UserDetailValue>{selectedRow?.designation || "—"}</UserDetailValue>
              </UserDetailField>
              <UserDetailField>
                <UserDetailLabel>Role</UserDetailLabel>
                <UserDetailValue>{selectedRow?.role || "—"}</UserDetailValue>
              </UserDetailField>
            </SettingsFormGrid>

            <SettingsFormGrid>
              <UserDetailField>
                <UserDetailLabel>Gender</UserDetailLabel>
                <UserDetailValue style={{ textTransform: "capitalize" }}>{selectedRow?.gender || "—"}</UserDetailValue>
              </UserDetailField>
              <UserDetailField>
                <UserDetailLabel>Category</UserDetailLabel>
                <UserDetailValue>
                  {selectedRow?.categoryId
                    ? AudienceOptions.find(o => o.value === selectedRow.categoryId)?.label || selectedRow.categoryId
                    : "—"}
                </UserDetailValue>
              </UserDetailField>
            </SettingsFormGrid>

            {selectedRow?.companyName && (
              <UserDetailField>
                <UserDetailLabel>Company</UserDetailLabel>
                <UserDetailValue>{selectedRow.companyName}</UserDetailValue>
              </UserDetailField>
            )}

            <SettingsFormGrid>
              {selectedRow?.businessUnit && (
                <UserDetailField>
                  <UserDetailLabel>Business Unit</UserDetailLabel>
                  <UserDetailValue>{selectedRow.businessUnit}</UserDetailValue>
                </UserDetailField>
              )}
              {selectedRow?.division && (
                <UserDetailField>
                  <UserDetailLabel>Division</UserDetailLabel>
                  <UserDetailValue>{selectedRow.division}</UserDetailValue>
                </UserDetailField>
              )}
            </SettingsFormGrid>

            {selectedRow?.departmentId && (
              <UserDetailField>
                <UserDetailLabel>Department</UserDetailLabel>
                <UserDetailValue>{selectedRow.departmentId}</UserDetailValue>
              </UserDetailField>
            )}

            <UserDetailField>
              <UserDetailLabel>Joining Date</UserDetailLabel>
              <UserDetailValue>
                <i className="fas fa-calendar" style={{ fontSize: 11, color: "#3f88a5" }} />
                {selectedRow?.joiningDate
                  ? new Date(selectedRow.joiningDate).toLocaleDateString()
                  : "Not available"}
              </UserDetailValue>
            </UserDetailField>

            {selectedRow?.location?.length > 0 && (
              <div style={{ marginTop: "16px" }}>
                <UserDetailLabel>Assigned Locations</UserDetailLabel>

                {/* Search box for locations */}
                <div style={{ position: "relative", marginTop: "6px", marginBottom: "8px" }}>
                  <i className="fas fa-search" style={{ position: "absolute", left: "10px", top: "50%", transform: "translateY(-50%)", fontSize: "11px", color: "#64748b" }} />
                  <input
                    type="text"
                    placeholder="Search locations..."
                    value={locationSearchQuery}
                    onChange={(e) => setLocationSearchQuery(e.target.value)}
                    style={{
                      width: "100%",
                      padding: "8px 12px 8px 30px",
                      fontSize: "12.5px",
                      border: "1.5px solid #e2e8f0",
                      borderRadius: "8px",
                      outline: "none",
                      background: "#fff",
                      color: "#1e293b",
                    }}
                  />
                  {locationSearchQuery && (
                    <button
                      type="button"
                      onClick={() => setLocationSearchQuery("")}
                      style={{
                        position: "absolute",
                        right: "10px",
                        top: "50%",
                        transform: "translateY(-50%)",
                        border: "none",
                        background: "none",
                        cursor: "pointer",
                        fontSize: "11px",
                        color: "#94a3b8",
                      }}
                    >
                      <i className="fas fa-times" />
                    </button>
                  )}
                </div>

                {/* Unified scrollable vertical locations list */}
                <div
                  style={{
                    maxHeight: "180px",
                    overflowY: "auto",
                    borderRadius: "9px",
                    border: "1.5px solid #e2e8f0",
                    background: "#f8fafc",
                    boxShadow: "inset 0 1px 2px rgba(0,0,0,0.02)",
                  }}
                  className="custom-scrollbar"
                >
                  {renderLocationTab()}
                </div>
              </div>
            )}
          </SettingsModalBody>
          <SettingsModalFooter>
            <SecondaryButton onClick={() => setShowModalUserDetail(false)}>Close</SecondaryButton>
          </SettingsModalFooter>
        </Modal>
      )}

      {/* ── Add user modal ─────────────────────────────────────────────────── */}
      <Modal show={addNewUserPopup} onClose={handleCloseNewUserPopup} maxWidth={620}>
        <ModalHeader
          icon="fas fa-user-plus"
          title="Add New User"
          subtitle="Fill in the details to invite a new user"
          onClose={handleCloseNewUserPopup}
        />
        <SettingsModalBody>
          <SettingsFormGrid>
            <SettingsFormGroup>
              <SettingsFormLabel>First Name *</SettingsFormLabel>
              <SettingsFormInput $accent placeholder="First Name" name="firstName" type="text" onChange={handleChange} />
              {submitted && !userDetails.firstName && (
                <span style={{ fontSize: 11, color: "#dc2626" }}>First Name is required</span>
              )}
            </SettingsFormGroup>
            <SettingsFormGroup>
              <SettingsFormLabel>Last Name</SettingsFormLabel>
              <SettingsFormInput placeholder="Last Name" name="lastName" type="text" onChange={handleChange} />
            </SettingsFormGroup>
          </SettingsFormGrid>

          <SettingsFormGrid>
            <SettingsFormGroup>
              <SettingsFormLabel>Email *</SettingsFormLabel>
              <SettingsFormInput $accent placeholder="Email" name="emailId" type="email" onChange={handleChange} />
              {submitted && !userDetails.emailId && (
                <span style={{ fontSize: 11, color: "#dc2626" }}>Email is required</span>
              )}
            </SettingsFormGroup>
            <SettingsFormGroup>
              <SettingsFormLabel>Employee ID</SettingsFormLabel>
              <SettingsFormInput $accent placeholder="Employee ID" name="employeeId" type="number" onChange={handleChange} />
            </SettingsFormGroup>
          </SettingsFormGrid>

          <SettingsFormGrid>
            <SettingsFormGroup>
              <SettingsFormLabel>Role *</SettingsFormLabel>
              <MultiSelectDropdown
                options={mappedRoleOptions}
                selected={roleIds}
                onChange={setRoleIds}
                placeholder="Search and select roles…"
                searchPlaceholder="Type to search roles…"
              />
              {submitted && roleIds.length === 0 && !newRoleName && (
                <span style={{ fontSize: 11, color: "#dc2626" }}>Role is required</span>
              )}
            </SettingsFormGroup>
            <SettingsFormGroup>
              <SettingsFormLabel>Gender *</SettingsFormLabel>
              <SettingsFormSelect value={gender} onChange={e => setGender(e.target.value)}>
                <option value="">Select Gender</option>
                <option value="MALE">Male</option>
                <option value="FEMALE">Female</option>
                <option value="OTHER">Other</option>
              </SettingsFormSelect>
            </SettingsFormGroup>
          </SettingsFormGrid>

          {roleId != 30 && (
            <SettingsFormGrid>
              <SettingsFormGroup>
                <SettingsFormLabel>Mobile</SettingsFormLabel>
                <PhoneInput country={"in"} value={phone} onChange={p => setPhone(p)} enableSearch />
              </SettingsFormGroup>
            </SettingsFormGrid>
          )}

          <SettingsFormGrid>
            <SettingsFormGroup>
              <SettingsFormLabel>Joining Date</SettingsFormLabel>
              <SettingsFormInput
                $accent
                type="date"
                max={new Date().toISOString().split("T")[0]}
                value={joiningDate}
                onChange={e => setJoiningDate(e.target.value)}
              />
            </SettingsFormGroup>
          </SettingsFormGrid>

          {companyId == 362 && (
            <>
              <SettingsFormGrid>
                <SettingsFormGroup>
                  <SettingsFormLabel>Category</SettingsFormLabel>
                  <SettingsFormSelect value={categoryId} onChange={e => setCategoryId(e.target.value)}>
                    <option value="">Select Category</option>
                    {AudienceOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                  </SettingsFormSelect>
                </SettingsFormGroup>
                <SettingsFormGroup>
                  <SettingsFormLabel>Company</SettingsFormLabel>
                  <SettingsFormSelect value={companyName} onChange={e => setCompanyName(e.target.value)}>
                    <option value="">Select Company</option>
                    {companyOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                  </SettingsFormSelect>
                </SettingsFormGroup>
              </SettingsFormGrid>

              <SettingsFormGrid>
                <SettingsFormGroup>
                  <SettingsFormLabel>Business Unit</SettingsFormLabel>
                  <SettingsFormSelect value={businessUnit} onChange={e => setBusinessUnit(e.target.value)}>
                    <option value="">Select Business Unit</option>
                    {businessUnitOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                  </SettingsFormSelect>
                </SettingsFormGroup>
                <SettingsFormGroup>
                  <SettingsFormLabel>Division</SettingsFormLabel>
                  <SettingsFormSelect value={division} onChange={e => setDivision(e.target.value)}>
                    <option value="">Select Division</option>
                    {divisionOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                  </SettingsFormSelect>
                </SettingsFormGroup>
              </SettingsFormGrid>

              <SettingsFormGrid>
                <SettingsFormGroup>
                  <SettingsFormLabel>Department</SettingsFormLabel>
                  <SettingsFormSelect value={departmentId} onChange={e => setDepartmentId(e.target.value)}>
                    <option value="">Select Department</option>
                    {departmentOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                  </SettingsFormSelect>
                </SettingsFormGroup>
              </SettingsFormGrid>
            </>
          )}
        </SettingsModalBody>
        <SettingsModalFooter>
          <SecondaryButton onClick={handleCloseNewUserPopup}>Cancel</SecondaryButton>
          <PrimaryButton
            disabled={updateLoader || !userDetails?.firstName || !userDetails?.emailId || (roleIds.length === 0 && !newRoleName) || !gender}
            onClick={sendInvite}
          >
            {updateLoader ? <><Spinner animation="border" size="sm" style={{ marginRight: 6 }} />Sending…</> : "Add User"}
          </PrimaryButton>
        </SettingsModalFooter>
      </Modal>

      <Modal show={convertPopup} onClose={handleCloseConvertPopup} maxWidth={560}>
        <ModalHeader
          icon="fas fa-user-check"
          title="Convert to Employee"
          subtitle="Assign roles and add the selected trainees as employees — all selected trainees will receive the combined role set"
          onClose={handleCloseConvertPopup}
        />
        <SettingsModalBody style={{ overflow: "visible" }}>
          <SettingsFormGroup>
            <SettingsFormLabel>
              Trainees *
              {convertUserIds.length > 0 && (
                <span style={{ marginLeft: 6, fontWeight: 400, color: "#94a3b8" }}>
                  ({convertUserIds.length} selected)
                </span>
              )}
            </SettingsFormLabel>
            <MultiSelectDropdown
              options={convertUserOptions}
              selected={convertUserIds}
              onChange={handleConvertUsersChange}
              placeholder={convertListLoading ? "Loading trainees…" : "Search and select trainees…"}
              searchPlaceholder="Type to search trainees…"
            />
            {!convertListLoading && convertListError && (
              <span style={{ fontSize: 11, color: "#dc2626", display: "inline-flex", alignItems: "center", gap: 6 }}>
                <i className="fas fa-exclamation-circle" aria-hidden="true" />
                Couldn't load trainees.
                <button
                  type="button"
                  onClick={getConvertibleTrainees}
                  style={{ border: "none", background: "none", padding: 0, color: "#3f88a5", cursor: "pointer", fontSize: 11, fontWeight: 600, textDecoration: "underline" }}
                >
                  Retry
                </button>
              </span>
            )}
            {!convertListLoading && !convertListError && convertUserOptions.length === 0 && (
              <span style={{ fontSize: 11, color: "#94a3b8" }}>No trainees available to convert.</span>
            )}
            {convertSubmitted && convertUserIds.length === 0 && (
              <span style={{ fontSize: 11, color: "#dc2626" }}>Please select at least one trainee</span>
            )}
          </SettingsFormGroup>

          {convertUserIds.length > 0 && (
          <SettingsFormGroup>
            <SettingsFormLabel>Role *</SettingsFormLabel>
            <MultiSelectDropdown
              options={mappedRoleOptions}
              selected={convertRoleIds}
              onChange={setConvertRoleIds}
              placeholder="Search and select roles…"
              searchPlaceholder="Type to search roles…"
            />
            {convertSubmitted && convertRoleIds.length === 0 && (
              <span style={{ fontSize: 11, color: "#dc2626" }}>Role is required</span>
            )}
          </SettingsFormGroup>
          )}
        </SettingsModalBody>
        <SettingsModalFooter>
          <SecondaryButton onClick={handleCloseConvertPopup}>Cancel</SecondaryButton>
          <PrimaryButton
            disabled={convertLoader || convertUserIds.length === 0 || convertRoleIds.length === 0}
            onClick={convertTraineeToEmployee}
          >
            {convertLoader ? <><Spinner animation="border" size="sm" style={{ marginRight: 6 }} />Converting…</> : "Convert to Employee"}
          </PrimaryButton>
        </SettingsModalFooter>
      </Modal>

      {/* ── Edit user modal ─────────────────────────────────────────────────── */}
      <Modal show={editUserPopup} onClose={() => setEditUserPopup(false)} maxWidth={620}>
        <ModalHeader
          icon="fas fa-user-edit"
          title="Edit User Details"
          subtitle="Update sub-user profile details and corporate roles"
          onClose={() => setEditUserPopup(false)}
        />
        <SettingsModalBody>
          <SettingsFormGrid>
            <SettingsFormGroup>
              <SettingsFormLabel>First Name *</SettingsFormLabel>
              <SettingsFormInput
                $accent
                placeholder="First Name"
                value={editUserDetails.firstName}
                type="text"
                onChange={e => setEditUserDetails(prev => ({ ...prev, firstName: e.target.value }))}
              />
              {submitted && !editUserDetails.firstName && (
                <span style={{ fontSize: 11, color: "#dc2626" }}>First Name is required</span>
              )}
            </SettingsFormGroup>
            <SettingsFormGroup>
              <SettingsFormLabel>Last Name</SettingsFormLabel>
              <SettingsFormInput
                placeholder="Last Name"
                value={editUserDetails.lastName}
                type="text"
                onChange={e => setEditUserDetails(prev => ({ ...prev, lastName: e.target.value }))}
              />
            </SettingsFormGroup>
          </SettingsFormGrid>

          <SettingsFormGrid>
            <SettingsFormGroup>
              <SettingsFormLabel>Email *</SettingsFormLabel>
              <SettingsFormInput
                $accent
                placeholder="Email"
                value={editUserDetails.emailId}
                type="email"
                onChange={e => setEditUserDetails(prev => ({ ...prev, emailId: e.target.value }))}
              />
              {submitted && !editUserDetails.emailId && (
                <span style={{ fontSize: 11, color: "#dc2626" }}>Email is required</span>
              )}
            </SettingsFormGroup>
            <SettingsFormGroup>
              <SettingsFormLabel>Employee ID</SettingsFormLabel>
              <SettingsFormInput
                $accent
                placeholder="Employee ID"
                value={editUserDetails.employeeId}
                type="text"
                onChange={e => setEditUserDetails(prev => ({ ...prev, employeeId: e.target.value }))}
              />
            </SettingsFormGroup>
          </SettingsFormGrid>

          <SettingsFormGrid>
            <SettingsFormGroup>
              <SettingsFormLabel>Role *</SettingsFormLabel>
              <MultiSelectDropdown
                options={mappedRoleOptions}
                selected={editRoleIds}
                onChange={setEditRoleIds}
                placeholder="Search and select roles…"
                searchPlaceholder="Type to search roles…"
              />
              {submitted && editRoleIds.length === 0 && !editNewRoleName && (
                <span style={{ fontSize: 11, color: "#dc2626" }}>Role is required</span>
              )}
            </SettingsFormGroup>
            <SettingsFormGroup>
              <SettingsFormLabel>Gender *</SettingsFormLabel>
              <SettingsFormSelect value={editGender} onChange={e => setEditGender(e.target.value)}>
                <option value="">Select Gender</option>
                <option value="MALE">Male</option>
                <option value="FEMALE">Female</option>
                <option value="OTHER">Other</option>
              </SettingsFormSelect>
            </SettingsFormGroup>
          </SettingsFormGrid>



          {editRoleId != 30 && (
            <SettingsFormGrid>
              <SettingsFormGroup>
                <SettingsFormLabel>Mobile</SettingsFormLabel>
                <PhoneInput country={"in"} value={editPhone} onChange={p => setEditPhone(p)} enableSearch />
              </SettingsFormGroup>
            </SettingsFormGrid>
          )}

          <SettingsFormGrid>
            <SettingsFormGroup>
              <SettingsFormLabel>Joining Date</SettingsFormLabel>
              <SettingsFormInput
                $accent
                type="date"
                max={new Date().toISOString().split("T")[0]}
                value={editJoiningDate}
                onChange={e => setEditJoiningDate(e.target.value)}
              />
            </SettingsFormGroup>
          </SettingsFormGrid>

          {companyId == 362 && (
            <>
              <SettingsFormGrid>
                <SettingsFormGroup>
                  <SettingsFormLabel>Category</SettingsFormLabel>
                  <SettingsFormSelect value={editCategoryId} onChange={e => setEditCategoryId(e.target.value)}>
                    <option value="">Select Category</option>
                    {AudienceOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                  </SettingsFormSelect>
                </SettingsFormGroup>
                <SettingsFormGroup>
                  <SettingsFormLabel>Company</SettingsFormLabel>
                  <SettingsFormSelect value={editCompanyName} onChange={e => setEditCompanyName(e.target.value)}>
                    <option value="">Select Company</option>
                    {companyOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                  </SettingsFormSelect>
                </SettingsFormGroup>
              </SettingsFormGrid>

              <SettingsFormGrid>
                <SettingsFormGroup>
                  <SettingsFormLabel>Business Unit</SettingsFormLabel>
                  <SettingsFormSelect value={editBusinessUnit} onChange={e => setEditBusinessUnit(e.target.value)}>
                    <option value="">Select Business Unit</option>
                    {businessUnitOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                  </SettingsFormSelect>
                </SettingsFormGroup>
                <SettingsFormGroup>
                  <SettingsFormLabel>Division</SettingsFormLabel>
                  <SettingsFormSelect value={editDivision} onChange={e => setEditDivision(e.target.value)}>
                    <option value="">Select Division</option>
                    {divisionOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                  </SettingsFormSelect>
                </SettingsFormGroup>
              </SettingsFormGrid>

              <SettingsFormGrid>
                <SettingsFormGroup>
                  <SettingsFormLabel>Department</SettingsFormLabel>
                  <SettingsFormSelect value={editDepartmentId} onChange={e => setEditDepartmentId(e.target.value)}>
                    <option value="">Select Department</option>
                    {departmentOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                  </SettingsFormSelect>
                </SettingsFormGroup>
              </SettingsFormGrid>
            </>
          )}
        </SettingsModalBody>
        <SettingsModalFooter>
          <SecondaryButton onClick={() => setEditUserPopup(false)}>Cancel</SecondaryButton>
          <PrimaryButton
            disabled={updateLoader || !editUserDetails?.firstName || !editUserDetails?.emailId || (editRoleIds.length === 0 && !editNewRoleName) || !editGender}
            onClick={updateSubUser}
          >
            {updateLoader ? <><Spinner animation="border" size="sm" style={{ marginRight: 6 }} />Updating…</> : "Save Changes"}
          </PrimaryButton>
        </SettingsModalFooter>
      </Modal>

      {/* ── Add location modal ─────────────────────────────────────────────── */}
      <Modal show={addNewLocationPopup} onClose={handleCloseLocationPopup} maxWidth={650}>
        <ModalHeader
          icon="fas fa-map-marker-alt"
          title="Add Location"
          subtitle="Assign one or more locations or sub-locations to this user"
          onClose={handleCloseLocationPopup}
        />

        <SettingsModalBody style={{ paddingBottom: 8, overflow: "visible", minHeight: "280px" }}>
          {/* Info strip */}


          <SettingsFormGroup>
            <SettingsFormLabel>
              Locations &amp; Sub-Locations
              {locationList.length > 0 && (
                <span style={{ marginLeft: 6, fontWeight: 400, color: "#94a3b8" }}>
                  ({locationList.length} available)
                </span>
              )}
            </SettingsFormLabel>

            <MultiSelectDropdown
              options={mappedLocationOptions}
              selected={source_ids}
              onChange={setSource_ids}
              placeholder="Search and select locations…"
              searchPlaceholder="Type to search locations…"
            />
          </SettingsFormGroup>


        </SettingsModalBody>

        <SettingsModalFooter>
          <SecondaryButton onClick={handleCloseLocationPopup}>Cancel</SecondaryButton>
          <PrimaryButton disabled={updateLoader || !source_ids.length} onClick={addLocation}>
            {updateLoader
              ? <><Spinner animation="border" size="sm" style={{ marginRight: 6 }} />Adding…</>
              : <>
                <i className="fas fa-plus" style={{ marginRight: 6, fontSize: 11 }} />
                Add {source_ids.length > 0 ? `${source_ids.length} ` : ""}Location{source_ids.length !== 1 ? "s" : ""}
              </>
            }
          </PrimaryButton>
        </SettingsModalFooter>
      </Modal>

      {/* ── Toggle status confirm ──────────────────────────────────────────── */}
      <Modal show={showModal} onClose={() => setShowModal(false)} maxWidth={420}>
        <ModalHeader
          icon={enable ? "fas fa-check-circle" : "fas fa-ban"}
          title={enable ? "Activate User?" : "Deactivate User?"}
          subtitle="Please confirm this action"
          onClose={() => setShowModal(false)}
        />
        <SettingsModalBody>
          <SettingsWarningBlock>
            {enable
              ? "Are you sure you want to activate this user?"
              : "Are you sure you want to deactivate this user? They will lose access immediately."}
          </SettingsWarningBlock>
        </SettingsModalBody>
        <SettingsModalFooter>
          <SecondaryButton onClick={() => setShowModal(false)}>No, cancel</SecondaryButton>
          <PrimaryButton onClick={actionUser}>
            {useLoader ? <Spinner animation="border" size="sm" /> : "Yes, confirm"}
          </PrimaryButton>
        </SettingsModalFooter>
      </Modal>

      {/* ── Delete location confirm ────────────────────────────────────────── */}
      <Modal show={deleteModal} onClose={() => setDeleteModal(false)} maxWidth={400}>
        <ModalHeader
          icon="fas fa-trash-alt"
          title={removeSubLocationId ? "Remove Sub-Location" : "Remove Location"}
          subtitle="This action cannot be undone"
          onClose={() => setDeleteModal(false)}
        />
        <SettingsModalBody>
          <SettingsWarningBlock>
            {removeSubLocationId
              ? "Are you sure you want to remove this sub-location from the user? Their other sub-locations at this site stay assigned."
              : "Are you sure you want to remove this location from the user?"}
          </SettingsWarningBlock>
        </SettingsModalBody>
        <SettingsModalFooter>
          <SecondaryButton onClick={() => setDeleteModal(false)}>Cancel</SecondaryButton>
          <DangerButton onClick={deleteLocation}>Delete</DangerButton>
        </SettingsModalFooter>
      </Modal>
    </SettingLayout>
  );
};

export default SubUsers;