import { TextField, Button, MenuItem, FormControl, Select } from "@mui/material";
import { Close } from "@mui/icons-material/";
import React, { useEffect, useState, useCallback, useRef } from "react";
import PropTypes from "prop-types";
import { toast } from "react-toastify";
import useApiService from "../services/apiService.js";
import { updateUser, getManageRole } from "../constants/apiEndPoints.js";
import { useUser } from "../context/UserContext.js";
import "../pages/ManageUsers.css";
import { UserStatus } from "../constants/userStatus.js";

function EditPopup({ onClose, firstName, lastName, role, email, userid, getUsersTable }) {
  const [editfirstName, setEditfirstName] = useState(String(firstName));
  const [editlastName, setEditlastName] = useState(String(lastName));
  const [allRoles, setAllRoles] = useState([]);
  const { user } = useUser();
  const { postApi } = useApiService();
  const [data, setData] = useState({});
  const [formData, setFormData] = useState({
    firstName: editfirstName,
    lastName: editlastName,
    email,
    role: role || "",
    status: "",
  });

  // Use useRef to ensure initialization only happens once
  const hasInitialized = useRef(false);

  const fetchAllRoles = useCallback(async (payload) => {
    console.log('🔵 EditPopup 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 (!hasInitialized.current) {
      hasInitialized.current = true;
      const payload = {
        Email: user?.user_email,
        SortType: "ASC",
        RoleId: null,
        PageNumber: 1,
        PageSize: 100,
        SortColumn: "Role_Name",
        Status: true,
      };
      fetchAllRoles(payload);
    }
  }, [fetchAllRoles]);

  const handleFirstNameChange = (e) => {
    setEditfirstName(e.target.value);
    setFormData({
      ...formData,
      firstName: e.target.value,
    });
  };

  const handleLastNameChange = (e) => {
    setEditlastName(e.target.value);
    setFormData({
      ...formData,
      lastName: e.target.value,
    });
  };

  const handleRoleChange = (event) => {
    setFormData({
      ...formData,
      role: event.target.value,
    });
  };

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

  const validate = () => {
    const formErrors = {};
    if (formData.firstName.trim() === "") {
      formErrors.firstName = "First name is required.";
    }
    if (formData.lastName?.trim() === "") {
      formErrors.lastName = "Last 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 (formData.role === "") {
      formErrors.role = "Role is required";
    }
    return formErrors;
  };

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

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

      const result = await postApi(updateUser, filter);
      setData(result || []);

      if (result?.IsSuccess) {
        toast.success("User edited successfully!");
      } else if (!result?.IsSuccess) {
        toast.error(result.Message);
      }
    } catch (error) {
      console.log("Error", error.message);
    }

    onClose();
    getUsersTable();
  };

  return (
    <div>
      <div className="popup-content edit-popup">
        <div className="d-flex headingpop">
          <h3>Edit User</h3>
          <Button onClick={onClose} data-testid="close-button">
            <Close data-testid="close-icon" />
          </Button>
        </div>
        <form>
          <div className="field">
            <div>
              First Name<span className="colorRed">*</span>
            </div>
            <TextField
              hiddenLabel
              placeholder="First Name"
              variant="filled"
              size="small"
              className="input"
              name="firstName"
              value={editfirstName}
              onChange={handleFirstNameChange}


            />
            {errors.firstName && (
              <span style={{ color: "red", fontSize: "12px", fontWeight: "400" }}>
                {errors.firstName}
              </span>
            )}
          </div>

          <div className="field">
            <div>
              Last Name<span className="colorRed">*</span>
            </div>
            <TextField
              hiddenLabel
              placeholder="Last Name"
              variant="filled"
              size="small"
              className="input"
              name="lastName"
              value={editlastName}
              onChange={handleLastNameChange}
            />
            {errors.lastName && (
              <span style={{ color: "red", fontSize: "12px", fontWeight: "400" }}>
                {errors.lastName}
              </span>
            )}
          </div>

          <div className="field">
            <div>
              Role<span className="colorRed">*</span>
            </div>
            <FormControl sx={{ minWidth: 120, width: "100%" }}>
              <Select
                value={formData.role}
                onChange={handleRoleChange}
                displayEmpty
                inputProps={{ "aria-label": "Without label" }}
                style={{ width: "100%", height: "40px" }}
              >
                {allRoles.map((e) => (
                  <MenuItem key={e.Role_Id} value={e.Role_Id}>
                    {e.RoleName}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            {errors.role && (
              <span style={{ color: "red", fontSize: "12px", fontWeight: "400" }}>
                {errors.role}
              </span>
            )}
          </div>

          <div style={{ display: "flex", justifyContent: "end" }} className="field left-align">
            <Button variant="contained" type="submit" data={data} onClick={handleSubmit}>
              Update User
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}


EditPopup.propTypes = {
  onClose: PropTypes.func.isRequired,
  firstName: PropTypes.string,
  lastName: PropTypes.string,
  role: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  email: PropTypes.string.isRequired,
  userid: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
  getUsersTable: PropTypes.func.isRequired,
};


EditPopup.defaultProps = {
  firstName: "",
  lastName: "",
  role: "",
};

export default EditPopup;
