import React, { useState } from "react";
import {
  Dialog,
  DialogTitle,
  DialogContent,
  TextField,
  Button,
  Typography,
  Radio,
  RadioGroup,
  FormControlLabel,
  FormLabel,
  Tooltip,
  IconButton,
} from "@mui/material";
import PropTypes from "prop-types";
import { Close } from "@mui/icons-material";
import { UserRoleHeirarchy } from "../../constants/userStatus.js";
import { permissionTypes } from "../../constants/userConstants.js";
import "./CreateRole.css"

export function CreateEditRoleDialog(props) {
  const {
    open,
    onClose,
    roleData,
    showPermissions,
    roleName,
    handleRoleSave,
    viewType,
    setRoleName,
    setViewType,
    permissions,
    handlePermissionSave,
    handlePermissionChange,
    oldViewtype,
    setShowPermissions,
  } = props

  const [isHovered, setIsHovered] = useState(false);

  const isDisabled = () => {
    if (!roleData?.RoleId && !roleData?.Role_Id) {
      return !roleName.trim()
    }
    if (roleData?.RoleId || roleData?.Role_Id) {
      if (roleName.trim() != roleData?.RoleName) { return false }
      if (viewType != oldViewtype) {
        return false
      }
       return true 
    }
  }


  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="md"
      className="manageRolesPopup"
      fullWidth
    >
      <DialogTitle className="role-title">
        {roleData ? "Edit Role" : "Create Role"}
      </DialogTitle>
      <IconButton
        aria-label="close"
        onClick={onClose}
        sx={(theme) => ({
          position: "absolute",
          right: 8,
          top: 8,
          color: theme.palette.grey[500],
        })}
      >
        <Close />
      </IconButton>
      <DialogContent className="role-dialog-content">
        {!showPermissions ? (
          <div className="role-name-section">
            <TextField
              label="Role Name"
              value={roleName}
              onChange={(e) => {
                const input = e.target.value;
                // Allow only letters and single spaces between words while typing
                const regex = /^[A-Za-z ]*$/;
                if (regex.test(input)) {
                  setRoleName(input.replaceAll(/\s{2,}/g, " ")); // Replace multiple spaces with single
                }
              }}
              fullWidth
              margin="normal"
              className="role-name-input"
              autoComplete="off"
              InputProps={{
                endAdornment: roleName && (
                  <span
                    style={{
                      display: "flex",
                      alignItems: "center",
                      marginLeft: 4,
                      paddingRight: "12px"
                    }}
                  >
                    <Tooltip
                      title="Role names can only contain letters and a single space between words."
                      style={{ cursor: "pointer", zIndex: 9 }}
                    >
                      <svg
                        width="18"
                        height="18"
                        viewBox="0 0 24 24"
                        fill="none"
                        id="icon-sv"
                      >
                        <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>
                ),
              }}
            />
            <div className="role-type-section">
              <FormLabel id="demo-radio-buttons-group-label">
                View Type Permission
              </FormLabel>
              <RadioGroup
                row
                name="role-type"
                value={
                  roleData?.ViewType || viewType || UserRoleHeirarchy[2].key
                }
                onChange={(e) => setViewType(e.target.value)}
                className="role-type-group"
              >
                {UserRoleHeirarchy.map((role) => (
                  <FormControlLabel
                    key={role.key}
                    value={role.key}
                    control={<Radio />}
                    label={role.value}
                  />
                ))}
              </RadioGroup>
            </div>
            <div className="role-actions">
               {(roleData?.RoleId || roleData?.Role_Id) &&  (
                <span style={{ display: "flex", justifyContent: "center" }}>
                  <button
                    onClick={(e) => {
                      e.preventDefault();
                      setShowPermissions(true); 
                    }}
                    onMouseEnter={() => setIsHovered(true)}
                    onMouseLeave={() => setIsHovered(false)}
                    style={{
                      cursor: "pointer",
                      color: isHovered ? "black" : "#1976d2",
                      textDecoration: "none",
                      textAlign: "center",
                      padding: "10px",
                      marginRight: "10px",
                      background: "none",
                      border: "none",
                      fontSize: "16px",
                      fontWeight: "500"

                    }}
                  >
                    EDIT PERMISSIONS
                  </button>
                </span>
              )}

              <Button
                disabled={isDisabled()}
                variant="contained"
                onClick={handleRoleSave}
                className="save-role-btn"
              >
                {`${roleData?.RoleId || roleData?.Role_Id ? "Update" : "Save"}`}
              </Button>
            </div>
          </div>
        ) : (
          <div className="permissions-container">
            <div className="module-list">
              {permissions.map((module, index) => (
                <div className="module-card" key={module.FeatureSubId}>
                  <Typography className="module-name">
                    {module.SubFeatureName}
                  </Typography>
                  <RadioGroup
                    row
                    name={`permissions-${index}`}
                    value={module.selectedPermission ?? ""}
                    onChange={(e) =>
                      handlePermissionChange(index, Number(e.target.value))
                    }
                  >
                    {permissionTypes.map((type) => (
                      <FormControlLabel
                        key={type.key}
                        value={type.key}
                        control={<Radio />}
                        label={type.value}
                      />
                    ))}
                  </RadioGroup>
                </div>
              ))}
            </div>
            <div className="permissions-actions">
              <Button
                variant="contained"
                onClick={handlePermissionSave}
                className="save-permissions-btn"
              >
                Update Permissions
              </Button>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}

CreateEditRoleDialog.propTypes = {
  open: PropTypes.bool.isRequired,
  onClose: PropTypes.func.isRequired,
  roleData: PropTypes.shape({
    RoleId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    Role_Id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    RoleName: PropTypes.string,
    ViewType: PropTypes.string,
  }),
  showPermissions: PropTypes.bool.isRequired,
  roleName: PropTypes.string.isRequired,
  handleRoleSave: PropTypes.func.isRequired,
  viewType: PropTypes.string.isRequired,
  setRoleName: PropTypes.func.isRequired,
  setViewType: PropTypes.func.isRequired,
  permissions: PropTypes.arrayOf(
    PropTypes.shape({
      FeatureSubId: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
        .isRequired,
      SubFeatureName: PropTypes.string.isRequired,
      selectedPermission: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    })
  ).isRequired,
  handlePermissionSave: PropTypes.func.isRequired,
  handlePermissionChange: PropTypes.func.isRequired,
  oldViewtype: PropTypes.string,
  setShowPermissions: PropTypes.func,
};

