import React, { useEffect, useState } from 'react';
import { TextInput } from '../../components/common/inputs/TextInput';
import { Search } from '../../components/common/inputs/Search';
import { CheckboxWlabel } from '../../components/common/inputs/Checkbox';
import {
  NofillButton,
  PrimaryButton,
} from '../../components/common/buttons/PrimaryBtn';
import { connect } from 'react-redux';
import {
  addNewAgentGroup,
  getAllAgents,
} from '../../redux/action-creators/agent-actions/agent-actions';
import { useToasts } from 'react-toast-notifications';
import { AvatarWTextCheckbox } from '../../components/common/avatars/AvatarWText';

const NewAgentGroup = ({
  setAddAgentGrpModal,
  addNewAgentGroup,
  getAllAgents,
  getAllNewAgentGroup,
  allAgents,
}) => {
  const [sendingInvite, setSendingInvite] = useState(false);
  const [name, setName] = useState('');
  const [agentsInGroup, addAgentsToGroup] = useState([]);
  const [selectAllAgents, setSelectAllagents] = useState(false);
  const [selectedAgentsDetails, setSelectedAgentsDetails] = useState([]);

  const { addToast } = useToasts();

  const checkSelected = _id => {
    if (agentsInGroup.includes(_id)) {
      return true;
    } else {
      return false;
    }
  };

  const addOrRemoveAgentFromGroup = agent => {
    let tempSelectedId = [];
    let tempSelectedDetails = [];
    if (agentsInGroup.includes(agent?._id)) {
      tempSelectedId = agentsInGroup.filter(agentId => {
        return agentId !== agent._id;
      });
      tempSelectedDetails = selectedAgentsDetails.filter(agentId => {
        return agentId?._id !== agent?._id;
      });
      addAgentsToGroup(tempSelectedId);
      setSelectedAgentsDetails(tempSelectedDetails);
    } else {
      tempSelectedId = [...agentsInGroup];
      tempSelectedDetails = [...selectedAgentsDetails];
      tempSelectedId.push(agent?._id);
      tempSelectedDetails.push(agent);
      addAgentsToGroup(tempSelectedId);
      setSelectedAgentsDetails(tempSelectedDetails);
    }
  };

  const onSelectAllAgent = selectAllAgents => {
    let copyAllAgent = [];
    setSelectAllagents(!selectAllAgents);
    if (selectAllAgents === false) {
      allAgents.agents.map(agent => {
        copyAllAgent.push(agent?._id);
      });
      setSelectedAgentsDetails(allAgents?.agents);
      addAgentsToGroup(copyAllAgent);
    } else {
      copyAllAgent = [];
      addAgentsToGroup(copyAllAgent);
      setSelectedAgentsDetails([]);
    }
  };

  const onAddNewAgentGroup = async () => {
    setSendingInvite(true);
    const inviteDetails = {
      name: name,
      // colour: '#ffffff',
      agents: agentsInGroup,
    };
    const inviteAgentGroupData = await addNewAgentGroup(inviteDetails);
    if (inviteAgentGroupData?.success) {
      getAllNewAgentGroup();
      addToast('Group created successfully', {
        appearance: 'success',
      });
      setAddAgentGrpModal(false);
      setName('');
      addAgentsToGroup([]);
    } else {
      addToast(`${inviteAgentGroupData?.error}`, {
        appearance: 'error',
      });
    }
    setSendingInvite(false);
  };

  useEffect(() => {
    const OnGetAllAgents = async () => {
      const agentData = await getAllAgents();
      return agentData;
    };
    OnGetAllAgents();
  }, [getAllAgents]);

  return (
    <>
      <div className="px-4 border-bottom">
        <TextInput
          type="text"
          value={name}
          name="name"
          onchange={e => setName(e.target.value)}
          label="Agent Group name"
          placeholder="Enter agent name"
        />
      </div>
      <div className="px-4 border-bottom py-3">
        <Search placeholder="Search agent" className="bg-grey full-width" />
      </div>
      <div className="modal-body py-1 ">
        {allAgents?.agents?.length === 0 && (
          <h4> No Agent has been added yet!</h4>
        )}
        {allAgents?.agents?.length > 0 && (
          <ul className="modal-oveflow-wrap">
            {allAgents?.agents?.map((ag, i) => {
              return (
                <li className="py-2 border-bottom" key={i}>
                  <AvatarWTextCheckbox
                    type="checkbox"
                    onChange={() => addOrRemoveAgentFromGroup(ag)}
                    className="uk-checkbox"
                    checked={checkSelected(ag?._id)}
                    image="/images/avatar1.png"
                    initials="ya"
                    name="Azee Azi"
                    email={ag.email}
                    category="agents"
                  />
                </li>
              );
            })}
          </ul>
        )}
      </div>
      <div className="d-flx-alc-jsb alt-modal-footer">
        <CheckboxWlabel
          checked={selectAllAgents}
          onchange={() => {
            onSelectAllAgent(selectAllAgents);
          }}
          type="checkbox"
          label="Select all agents"
        />
        <div className="d-flx-alc modal-action-wrap px-0">
          <NofillButton
            title="Cancel"
            onclick={() => setAddAgentGrpModal(false)}
          />
          <PrimaryButton
            loading={sendingInvite}
            onclick={() => onAddNewAgentGroup()}
            text="Create group"
          />
        </div>
      </div>
    </>
  );
};

const mapStateToProps = state => ({
  allAgentsGroup: state.agents.allNewAgentsGroup,
  allAgents: state.agents.allAgents,
});

export default connect(mapStateToProps, { addNewAgentGroup, getAllAgents })(
  NewAgentGroup
);
