import React from "react";
import { TextField, Button, MenuItem, Select, Tooltip } from "@mui/material";
import PropTypes from "prop-types";
import { Close } from "@mui/icons-material/";
import "../pages/ManageUsers.css";

function PopupForm({ onClose, handleInputChange, setFormData, formData, onSubmit, errors, setErrors, allRoles , user}) {
  const handleSelectChange = (event) => {
    setFormData({
      ...formData,
      role: event.target.value,
    });
  };
  const handleFormSubmit = () => {
    const newErrors = { ...errors };

    // Check if role is selected
    if (!formData.role) {
      newErrors.role = "Role is required.";
    } else {
      delete newErrors.role; // Remove error if role is selected
    }

    // Check other fields and update errors accordingly
    if (!formData.firstName) {
      newErrors.firstName = "First Name is required.";
    } else {
      delete newErrors.firstName;
    }

    if (!formData.lastName) {
      newErrors.lastName = "Last Name is required.";
    } else {
      delete newErrors.lastName;
    }

    if (!formData.email) {
      newErrors.email = "Email is required.";
    }
    else if (
    user?.whitelistdomain &&
    !user.whitelistdomain
      .split(",")
      .some((domain) =>
        formData.email.toLowerCase().endsWith(`@${domain.trim().toLowerCase()}`)
      )
  ) {
    newErrors.email = "The domain you entered for this email address is not allowed";
  } 
    else {
      delete newErrors.email;
    }

    

    setErrors(newErrors);

    // If there are no errors, proceed with the submit logic
    if (Object.keys(newErrors)?.length === 0) {
      onSubmit();
    }
  };
  return (
    <div>
      <div className="popup-content">
        <div className="d-flex headingpop">
          <h3 id="add-user-title">Add User</h3>
          <Button onClick={onClose}>
            <Close />
          </Button>
        </div>
        <div className="field">
          <div>
            First Name<span className="colorRed">*</span>
          </div>
          <TextField
            hiddenLabel
            id="filled-hidden-label-small"
            placeholder="First Name"
            variant="filled"
            size="small"
            className="input"
            name="firstName"
            value={formData.firstName}
            onChange={handleInputChange}
          />
          {errors.firstName && <span style={{ color: "red", fontSize: "12px"  }}>{errors.firstName}</span>}
        </div>
        <div className="field">
          <div>
            Last Name<span className="colorRed">*</span>
          </div>
          <TextField
            hiddenLabel
            id="filled-hidden-label-small"
            placeholder="Last Name"
            variant="filled"
            size="small"
            className="input"
            name="lastName"
            value={formData.lastName}
            onChange={handleInputChange}
          />
          {errors.lastName && <span style={{ color: "red" , fontSize: "12px" }}>{errors.lastName}</span>}
        </div>
        <div className="field">
          <div>
            Email<span className="colorRed">*</span>
          </div>
          <TextField
            hiddenLabel
            id="filled-hidden-label-small"
            placeholder="Email"
            variant="filled"
            size="small"
            className="input email"
            name="email"
            value={formData.email}
            onChange={handleInputChange}
            InputProps={{
                            endAdornment: (
                              <span
                                className="info-icon"
                              >
                                <Tooltip
                                  title={`Allowed domains: ${user?.whitelistdomain}`}
                                  sx={{ zIndex: 2000 }}
                                >
                                  <svg
                                    width="18"
                                    height="18"
                                    viewBox="0 0 24 24"
                                    fill="none"
                                  >
                                    <circle cx="12" cy="12" r="12" fill="#1976d2" />
                                    <text
                                      x="12"
                                      y="17"
                                      textAnchor="middle"
                                      fontSize="15"
                                      fill="#fff"
                                      fontFamily="Arial"
                                      fontWeight="bold"
                                    >
                                      i
                                    </text>
                                  </svg>
                                </Tooltip>
                              </span>
                            ),
                          }}
          />
          {errors.email && <span style={{ color: "red", fontSize: "12px" }}>{errors.email}</span>}
        </div>
        <div className="field">
          <div>
            Role<span className="colorRed">*</span>
          </div>
          <div style={{ minWidth: 120, width: "100%" }}>
            <Select
              className="role-selection-input"
              value={formData.role}
              onChange={handleSelectChange}
              displayEmpty
              inputProps={{ "aria-label": "Without label" }}
              style={{ width: "100%", height: "40px" }}
            >
              <MenuItem key="default" value="" selected>
                  Select Role
              </MenuItem>
              {allRoles?.map((e) =>  e.Status !== "InActive" && (
                <MenuItem key={e.RoleName} value={e.Role_Id}>
                  {e.RoleName}
                </MenuItem>
              ))}
            </Select>
            {errors.role && <span style={{ color: "red" , fontSize: "12px" }}>{errors.role}</span>}
          </div>
        </div>

        <div style={{ display: "flex", justifyContent: "end" }} className="field left-align">
          <Button type="submit" onClick={handleFormSubmit}>
            Add User
          </Button>
        </div>
      </div>
    </div>
  );
}

PopupForm.propTypes = {
  onClose: PropTypes.func.isRequired,
  handleInputChange: PropTypes.func.isRequired,
  setFormData: PropTypes.func.isRequired,
  onSubmit: PropTypes.func.isRequired,
  formData: PropTypes.shape({
    firstName: PropTypes.string,
    lastName: PropTypes.string,
    email: PropTypes.string,
    role: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  }).isRequired,
  errors: PropTypes.shape({
    firstName: PropTypes.string,
    lastName: PropTypes.string,
    email: PropTypes.string,
    role: PropTypes.string,
  }).isRequired,
  setErrors: PropTypes.func.isRequired,
  allRoles: PropTypes.arrayOf(
    PropTypes.shape({
      RoleName: PropTypes.string.isRequired,
      Role_Id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
      Status: PropTypes.string,
    })
  ).isRequired,
  user: PropTypes.shape({
    whitelistdomain: PropTypes.string,
  }),
};

PopupForm.defaultProps = {
  user: { whitelistdomain: "" },
};

export default PopupForm;
