
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Popover, Typography } from '@mui/material';
import { MoreVert } from '@mui/icons-material/';
import { Loader } from 'rsuite';
import useApiService from "../services/apiService.js";
import { UserActiveInactive } from "../constants/apiEndPoints.js";
import EditPopup from './EditPopup.js';
import { consentType, userStatus } from '../constants/userConstants.js';
import { useUser } from '../context/UserContext.js';
import "./LineChart.css";
import ConsentPopup from '../common/ConsentPopup.js';

export default function ActionBtn({ userData, getUserData, getUsersTable }) {
  const { user } = useUser();
  const [anchorEl, setAnchorEl] = useState(null);
  const [isPopoverOpen, setIsPopoverOpen] = useState(false);
  const [selectedAction, setSelectedAction] = useState(null);
  const { postApi } = useApiService();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({});
  const [showPopup, setShowPopup] = useState(false);
  const [userDataForActiveDelete, setUserDataForActiveDelete] = useState(null);
  const [showConsentPopup, setShowConsentPopup] = useState(false);

  const [filterForActive, setFilterForActive] = useState({
    UserId: userData?.user_id || '',
    IsActive: true,
    UserStatus: '',
  });

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

  const handleActiveDelete = async (updatedFilter) => {
    setLoading(true);
    try {

      const setActiveValue =
        userDataForActiveDelete?.user_status === userStatus.Active.key
          ? userStatus.Deactive.key
          : userStatus.Active.key;
      const updatedFilterData = { ...filterForActive, UserStatus: setActiveValue, ...updatedFilter };
      setFilterForActive(updatedFilterData);
      await postApi(UserActiveInactive, updatedFilterData);
      getUserData();

    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const handleCloseForPopover = () => {
    setShowPopup(false);
  };

  const handleOpenPopover = (action, userData) => {
    setUserDataForActiveDelete(userData);
    setSelectedAction(action);
    setIsPopoverOpen(true);
  };

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleConfirm = () => {
    if (selectedAction == 'deactivate') {
      handleActiveDelete();
    }
    setIsPopoverOpen(false);
  };

  const handleCancel = () => {
    setIsPopoverOpen(false);
  };

  const open = Boolean(anchorEl);
  const id = open ? 'simple-popover' : undefined;

  useEffect(() => {
    handleConfirm();
  }, []);

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

  const handleCloseConsetPopup = () => {
    setShowConsentPopup(false);
  }

  const handleConfirmConsentPopup = async () => {
    setShowConsentPopup(false);
    setLoading(true);
    try {
      await postApi(UserActiveInactive, {
        UserId: userData?.user_id || '',
        Isdelete: true,
        UserStatus: userStatus.Deleted.key,
      });
      getUsersTable();
    } catch (error) {
      console.error("Error deleting user:", error);
    } finally {
      setLoading(false);
    }
  }

  const handleConsentPopup = () => {
    setShowConsentPopup(true);
  }

  return (
    <div className='action-button'>
  {/* Replace div with accessible button */}
  <button
    type="button"
    aria-describedby={id}
    onClick={handleClick}
    aria-label="More actions"
    className="icon-button"
  >
    <MoreVert />
  </button>

  <Popover
    id={id}
    open={open}
    anchorEl={anchorEl}
    onClose={handleClose}
    anchorOrigin={{
      vertical: 'bottom',
      horizontal: 'left',
    }}
  >
    <Typography>
      <div className="box">
        <button
          className="element"
          style={{ cursor: 'pointer' }}
          tabIndex={0}
          onClick={actionHandler}
          onKeyDown={(e) => {
            if (e.key === 'Enter' || e.key === ' ') {
              e.preventDefault();
              actionHandler();
            }
          }}
        >
          Edit
        </button>

        {showPopup && (
          <div className="popup">
            <EditPopup
              firstName={userData?.user_first_name || ''}
              lastName={userData?.user_last_name || ''}
              role={userData?.user_role_id || ''}
              userid={userData?.user_id || ''}
              onClose={handleCloseForPopover}
              handleInputChange={handleInputChange}
              email={userData?.user_email || ''}
              getUsersTable={getUsersTable}
            />
          </div>
        )}

        {userData?.user_email && user?.user_email && userData?.user_email !== user?.user_email && (
          <button
            className="element"
            style={{ cursor: 'pointer' }}
            tabIndex={0}
            onClick={() => handleOpenPopover('deactivate', userData)}
            onKeyDown={(e) => {
              if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                handleOpenPopover('deactivate', userData);
              }
            }}
          >
            {userData?.user_status === userStatus.Active.key ? 'Deactive' : 'Re-Active'}
          </button>
        )}

        {userData?.user_status !== userStatus.Deleted.key && (
          <button
            className="element"
            style={{ cursor: 'pointer' }}
            tabIndex={0}
            onClick={handleConsentPopup}
            onKeyDown={(e) => {
              if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                handleConsentPopup();
              }
            }}
          >
            Delete
          </button>
        )}

        {showConsentPopup && (
          <div className="popup">
            <ConsentPopup
              consentTypeAction={consentType.Consent}
              title="Delete User Confirmation"
              message="Are you sure you want to delete this user?"
              actionMessagePositive="Yes, Delete"
              actionMessageNegative="No, Cancel"
              onClose={handleCloseConsetPopup}
              onAccept={handleConfirmConsentPopup}
            />
          </div>
        )}

        {isPopoverOpen && (
          <div className="popup">
            <ConsentPopup
              consentTypeAction={consentType.Consent}
              title={`Confirm ${userData?.user_status === userStatus.Active.key ? 'Deactivation' : 'Re-Activation'}`}
              message={`Are you sure, you want to ${userData?.user_status === userStatus.Active.key ? 'deactivate' : 'reactivate'} this user?`}
              actionMessagePositive={`Yes, ${userData?.user_status === userStatus.Active.key ? 'Deactivate' : 'Reactivate'}`}
              actionMessageNegative="No, Cancel"
              onClose={handleCancel}
              onAccept={handleConfirm}
            />
          </div>
        )}
      </div>
    </Typography>
  </Popover>

  {loading && <Loader />}
</div>

  );
}

ActionBtn.propTypes = {
  userData: PropTypes.object.isRequired,
  getUserData: PropTypes.func.isRequired,
  getUsersTable: PropTypes.func.isRequired,
};
