import React, { useEffect, useMemo, useState } from 'react';
import PropTypes from 'prop-types';
import { addFriend as connect, removeFriend as disconnect } from '../../helpers/rest';
import { toast } from 'react-toastify';
import { Modal, ModalBody, ModalHeader, ModalFooter, Button, Tooltip } from 'reactstrap';
import { useBrowserQuery } from '../../context/BrowserQuery';
import { removeFriend } from '../../store/features/friendsSlice';
import { useDispatch } from 'react-redux';

const JKConnectButton = props => {
  const { user, currentUser, addContent, removeContent, cssClasses, color, size, outline } = props;
  const [isFriend, setIsFriend] = useState(false);
  const [pendingFriendRequest, setPendingFriendRequest] = useState(false);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [tooltipOpen, setTooltipOpen] = useState(false);
  const [isRemoving, setIsRemoving] = useState(false);
  const dispatch = useDispatch();

  useEffect(() => {
    if (user) {
      setIsFriend(user.is_friend);
      setPendingFriendRequest(user.pending_friend_request);
    }
  }, [user]);

  const queryString = useBrowserQuery();

  useEffect(() => {
    const openWin = queryString.get('open');
    const userId = queryString.get('id');
    //sending friend request if directly reqested to do so
    //by query string params (coming from weekly new user match email link)
    if (openWin && userId && userId === user.id && !user.isFriend && !user.pending_friend_request) {
      if (openWin === 'connect') {
        addFriend();
      }
    }
  }, []);

  const addFriend = () => {
    setShowConfirmModal(!showConfirmModal);
    setPendingFriendRequest(true);
    connect(
      currentUser.id,
      user.id
    )
      .then(resp => {
        if (resp.ok && resp.status === 201) {
          toast.success(`Success! Your friend request has been sent to ${user.name}.`);
        }
      })
      .catch(err => {
        toast.error('An error encountered when sending friend request.');
        setPendingFriendRequest(false);
      });
  };

  const confirm = () => {
    setShowConfirmModal(!showConfirmModal);
  };

  const unFriend = () => {
    setIsRemoving(true);
    disconnect(currentUser.id, user.id)
      .then(async resp => {
        if (resp.ok) {
          afterUnFriend();
          dispatch(removeFriend(user.id));
        }
      })
      .catch(err => {
        toast.error('An error encountered when removing friend');
        afterUnFriend();
      });
  };

  const afterUnFriend = () => {
    setIsFriend(false);
    setPendingFriendRequest(false);
    setIsRemoving(false);
    setShowConfirmModal(false);
  };

  const buttonTitle = useMemo(() => {
    let title = '';
    if (!isFriend && pendingFriendRequest) {
      title = 'Delete pending friend request';
    } else if (!isFriend) {
      title = 'Send friend request';
    } else if (isFriend) {
      title = 'Unfriend this person';
    }
    return title;
  }, [isFriend, pendingFriendRequest]);

  return (
    <>
      {!isFriend ? (
        <>
          <Button
            id={`connect-user-${user.id}`}
            onClick={addFriend}
            color={color}
            size={size}
            outline={outline}
            className={cssClasses}
            data-testid="connect"
            disabled={pendingFriendRequest}
          >
            {addContent}
          </Button>
          <Tooltip
            placement="top"
            isOpen={tooltipOpen}
            target={`connect-user-${user.id}`}
            toggle={() => setTooltipOpen(!tooltipOpen)}
          >
            {buttonTitle}
          </Tooltip>
          {/* <ConnectConfirmModal
            show={showConfirmModal}
            setShow={setShowConfirmModal}
            user={user}
            handleOnConfirm={addFriend}
          /> */}
        </>
      ) : (
        <>
          <Button
            id={`disconnect-user-${user.id}`}
            onClick={() => setShowConfirmModal(!showConfirmModal)}
            color={color}
            size={size}
            outline={outline}
            className={cssClasses}
            data-testid="disconnect"
          >
            {removeContent}
          </Button>
          <Tooltip
            placement="top"
            isOpen={tooltipOpen}
            target={`disconnect-user-${user.id}`}
            toggle={() => setTooltipOpen(!tooltipOpen)}
          >
            {buttonTitle}
          </Tooltip>
          <RemoveConfirmModal
            show={showConfirmModal}
            setShow={setShowConfirmModal}
            user={user}
            handleOnConfirm={unFriend}
            isRemoving={isRemoving}
          />
        </>
      )}
    </>
  );
};

JKConnectButton.propTypes = {
  user: PropTypes.object.isRequired,
  currentUser: PropTypes.object.isRequired,
  addContent: PropTypes.element.isRequired,
  removeContent: PropTypes.element.isRequired
};

JKConnectButton.defaultProps = {
  color: 'primary',
  size: 'sm',
  outline: false
};

// const ConnectConfirmModal = props => {
//   const { className, show, setShow, user, handleOnConfirm } = props;

//   //const [modal, setModal] = useState(show);

//   const toggle = () => setShow(!show);

//   const accept = () => {
//     handleOnConfirm();
//   };

//   return (

//       <Modal isOpen={show} toggle={toggle} className={className} centered={true} data-testid="confirmFriendRequestModal">
//         <ModalHeader toggle={toggle}>Send Friend Request</ModalHeader>
//         <ModalBody>Send a friend request to {user.name}.</ModalBody>
//         <ModalFooter>
//           <Button color="primary" onClick={accept}>
//             Yes
//           </Button>{' '}
//           <Button color="secondary" onClick={toggle}>
//             No
//           </Button>
//         </ModalFooter>
//       </Modal>

//   );
// };

const RemoveConfirmModal = props => {
  const { className, show, setShow, user, handleOnConfirm, isRemoving } = props;

  const toggle = () => setShow(!show);

  const accept = () => {
    handleOnConfirm();
  };

  return (
    <Modal isOpen={show} toggle={toggle} className={className} centered={true} data-testid="confirmRemoveFriendModal">
      <ModalHeader toggle={toggle}>Remove Friend</ModalHeader>
      <ModalBody>Are you sure to remove {user.name} from your friend list?</ModalBody>
      <ModalFooter>
        <Button color="primary" onClick={accept} disabled={isRemoving}>
          {isRemoving ? 'Removing...' : 'Yes'}
        </Button>{' '}
        <Button color="secondary" onClick={toggle} disabled={isRemoving}>
          Cancel
        </Button>
      </ModalFooter>
    </Modal>
  );
};

export default JKConnectButton;
