import React, { useEffect, useState } from 'react';
import ProfileSection from '../../components/common/wrappers/ProfileWrapper';
import {
  NofillButton,
  PrimaryButton,
} from '../../components/common/buttons/PrimaryBtn';
import { LargeModal } from '../modals/ModalWrapper.modal';
import { AgentsTabs } from '../navbar/Tabs';
import styled from 'styled-components';
import TagInputWODrop from '../../components/common/inputs/TagInputWODrop';
import { useToasts } from 'react-toast-notifications';
import {
  addAgents,
  addAgentsToAgentGroup,
  deleteAnAgent,
  deleteAnAgentGroup,
  disableAgent,
  getAllAgents,
  getAllAgentsInAGroup,
  getAllNewAgentGroup,
  removeAgentInGroup,
  searchAgent,
  searchAgentGroup,
  updateAgentGroup,
} from '../../redux/action-creators/agent-actions/agent-actions';
import { connect } from 'react-redux';
import { LinkPrimaryOutline } from '../../components/common/link-items/links';
import { FilterDrop } from '../../components/dropdowns/drop';
import { CheckboxWlabel } from '../../components/common/inputs/Checkbox';
import { Search } from '../../components/common/inputs/Search';
import { SelectDrop } from '../../components/common/inputs/SelectDrop';
import NewAgentGroup from '../agent-container/NewAgentGroup';
import { AgentGroupCard } from '../../components/cards/AgentGroupCard';
import { formatDistanceToNow } from 'date-fns';
import AgentInfoList from '../agent-container/AgentInfoList';
import { IconButton } from '../../components/common/buttons/IconButton';
import { InputWOLabel } from '../../components/common/inputs/TextInput';

const AgentMembers = ({
  addAgents,
  getAllAgents,
  allAgents,
  deleteAnAgent,
  disableAgent,
  searchAgent,
  searchResult,
  getAllNewAgentGroup,
  searchAgentGroup,
  searchedAgentGroupResult,
  agentGroups,
  deleteAnAgentGroup,
  addAgentsToAgentGroup,
  updateAgentGroup,
  removeAgentInGroup,
  getAllAgentsInAGroup,
  allAgentsInGroup,
}) => {
  const [addAgentModal, setAddAgentModal] = useState(false);
  const [addAgentGrpModal, setAddAgentGrpModal] = useState(false);
  const [inviteList, setUpdateList] = useState([]);
  const [sendingInvite, setSendingInvite] = useState(false);
  const [agentTabControl, setagentTabControl] = useState(true);

  const [showLocationFilter, setShowLocationFilter] = useState(false);
  const [showStatus, setShowStatus] = useState(false);
  const list = ['active', 'disabled'];

  const [searchText, setSearchText] = useState('');
  const [searchAgentG, setSearchAgentG] = useState('');
  const [currentPage, setCurrentPage] = useState(1);

  const nextPage = () => {
    if (currentPage < (allAgents?.count || agentGroups?.count)) {
      setCurrentPage(currentPage + 1);
    }
  };

  const previousPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  // const nextPageForGroup = () => {
  //   if (currentPage < agentGroups?.count) {
  //     setCurrentPage(currentPage + 1);
  //   }
  // };

  const handleAgentChange = () => {
    setagentTabControl(!agentTabControl);
  };
  const { addToast } = useToasts();

  const openAddAgentModal = () => {
    setAddAgentModal(true);
  };

  const onAddAgents = async () => {
    setSendingInvite(true);
    const inviteDetails = { emails: inviteList };
    const inviteAgentData = await addAgents(inviteDetails);
    if (inviteAgentData?.success) {
      getAllAgents();
      addToast(`${inviteAgentData?.data?.created} invites sent successfully`, {
        appearance: 'success',
      });
      setAddAgentModal(false);
      setUpdateList([]);
    } else {
      addToast(inviteAgentData?.error, {
        appearance: 'error',
      });
    }
    setSendingInvite(false);
  };

  const onGetSearchedAgent = async searchTerm => {
    const agentResult = await searchAgent(searchTerm);
    return agentResult;
  };

  const onGetSearchedAgentGroup = async searchTerm => {
    const agentGroupResult = await searchAgentGroup(searchTerm);
    return agentGroupResult;
  };
  useEffect(() => {
    if (searchText) {
      onGetSearchedAgent(searchText);
      onGetSearchedAgentGroup(searchAgentG);
    }
  }, [searchText, searchAgentG]);

  useEffect(() => {
    const OnGetAllAgents = async () => {
      const agentData = await getAllAgents(currentPage);
      return agentData;
    };
    const onGetAllAgentGroups = async () => {
      const agentGroupData = await getAllNewAgentGroup(
        currentPage,
        20,
        () => {}
      );
      return agentGroupData;
    };
    const onGetAllAgentsInAGroup = async () => {
      const agentsInAnAgentGroup = await getAllAgentsInAGroup();
      return agentsInAnAgentGroup;
    };

    OnGetAllAgents();
    onGetAllAgentGroups();
    onGetAllAgentsInAGroup();
  }, [getAllAgents, deleteAnAgent, getAllNewAgentGroup, getAllAgentsInAGroup]);

  const agentList = searchText?.length ? searchResult : allAgents;

  const agentGroupList = searchAgentG?.length
    ? searchedAgentGroupResult
    : agentGroups;

  return (
    <>
      <ProfileSection className="sectionw-details alt pb-0">
        <div className="section-details  d-flx-alc-jsb">
          <h3>Agents</h3>
          {agentTabControl ? (
            <div>
              <PrimaryButton
                text="Add new agent"
                onclick={() => setAddAgentModal(true)}
              />
              <LargeModal
                visible={addAgentModal}
                setvisible={setAddAgentModal}
                title="Add your agents"
                height={350}
              >
                <div className="modal-body overflow-y">
                  <TagInputWODrop
                    setUpdateList={setUpdateList}
                    placeholder="Enter agent email separated with comma"
                  />
                </div>
                <div className="d-flx-alc-jfe modal-action-wrap alt-modal-footer">
                  <NofillButton
                    title="cancel"
                    onclick={() => setAddAgentModal(false)}
                  />
                  <PrimaryButton
                    loading={sendingInvite}
                    onclick={() => onAddAgents()}
                    text="Send Invites"
                  />
                </div>
              </LargeModal>
            </div>
          ) : (
            <div>
              <PrimaryButton
                text="Add new agent group"
                onclick={() => setAddAgentGrpModal(true)}
              />
              <LargeModal
                visible={addAgentGrpModal}
                setvisible={setAddAgentGrpModal}
                title="Create an agent group"
                height={650}
              >
                <NewAgentGroup
                  setAddAgentGrpModal={setAddAgentGrpModal}
                  getAllNewAgentGroup={getAllNewAgentGroup}
                />
              </LargeModal>
            </div>
          )}
        </div>
        <div className="border-bottom">
          <AgentsTabs
            actions={handleAgentChange}
            agentTabControl={agentTabControl}
          />
        </div>
      </ProfileSection>

      <div>
        {agentTabControl ? (
          <>
            <div className="agent-helper-section py-3 border-bottom ">
              <div className="flx-jsb-rl">
                <CheckboxWlabel type="checkbox" label="Select all" />
                <div className="d-flx-alc-jsb">
                  <FilterDrop>
                    <ul className="drop-list">
                      <li
                        className="active"
                        onClick={() =>
                          setShowLocationFilter(!showLocationFilter)
                        }
                      >
                        <svg>
                          <use href="/images/icons.svg#check"></use>
                        </svg>
                        <span onClick={() => setShowLocationFilter(true)}>
                          Location
                        </span>
                      </li>
                      <li>
                        <svg>
                          <use href="/images/icons.svg#check"></use>
                        </svg>
                        <span>Dispatch name</span>
                      </li>
                      <li onClick={() => setShowStatus(!showStatus)}>
                        <svg>
                          <use href="/images/icons.svg#check"></use>
                        </svg>
                        <span onClick={() => setShowStatus(true)}>Status</span>
                      </li>
                      <li>
                        <svg>
                          <use href="/images/icons.svg#check"></use>
                        </svg>
                        <span>Agent name</span>
                      </li>
                    </ul>
                  </FilterDrop>
                  <Search
                    placeholder="Search agents... "
                    text={searchText}
                    onChange={val => setSearchText(val)}
                  />
                </div>
              </div>
              {showLocationFilter ? (
                <div className="flex-width-1-2 width-50r less-gp mt-3">
                  <SelectDrop
                    placeholder="Location"
                    type="text"
                    list={list}
                    className="input-height-40"
                  />
                  <SelectDrop
                    placeholder="Total responses"
                    type="text"
                    list={list}
                    className="input-height-40"
                  />
                </div>
              ) : (
                ''
              )}

              {showStatus ? (
                <div className="flex-width-1-2 width-50r less-gp mt-3">
                  <SelectDrop
                    placeholder="Filter by Active Status"
                    type="text"
                    list={list}
                    className="input-height-40"
                  />
                </div>
              ) : (
                ''
              )}
            </div>

            {agentList && agentList?.agents?.length === 0 && (
              <div className="empty-agent">
                <img src="/images/empty-agent.png" alt="" />
                <p className="mb-2">Add agents to help collect responses.</p>
                <LinkPrimaryOutline
                  as="button"
                  title="Add Agent"
                  onclick={() => openAddAgentModal()}
                />
              </div>
            )}

            {agentList && agentList?.agents?.length > 0 && (
              <AgentsList>
                {agentList &&
                  agentList?.agents?.map((agent, i) => {
                    return (
                      <>
                        <AgentInfoList
                          key={i}
                          agent={agent}
                          deleteAnAgent={deleteAnAgent}
                          getAllAgents={getAllAgents}
                          disableAgent={disableAgent}
                          addAgentsToAgentGroup={addAgentsToAgentGroup}
                        />
                      </>
                    );
                  })}
                <Pagination className="d-flx-alc">
                  <IconButton onclick={() => previousPage()} svg="arrow-left" />
                  <InputWOLabel disabled placeholder="0" value={currentPage} />
                  <span>/</span>
                  <span>{Math.ceil(agentList?.count / 20)}</span>
                  <IconButton svg="arrow-right" onclick={() => nextPage()} />
                </Pagination>
              </AgentsList>
            )}
          </>
        ) : (
          <>
            <div className="agent-helper-section py-3 border-bottom ">
              <div className="flx-jsb-rl">
                <CheckboxWlabel type="checkbox" label="Select all" />
                <div className="d-flx-alc-jsb">
                  <FilterDrop>
                    <ul className="drop-list">
                      <li
                        className="active"
                        onClick={() =>
                          setShowLocationFilter(!showLocationFilter)
                        }
                      >
                        <svg>
                          <use href="/images/icons.svg#check"></use>
                        </svg>
                        <span>Location</span>
                      </li>
                      <li>
                        <svg>
                          <use href="/images/icons.svg#check"></use>
                        </svg>
                        <span>Dispatch name</span>
                      </li>
                      <li>
                        <svg>
                          <use href="/images/icons.svg#check"></use>
                        </svg>
                        <span>Status</span>
                      </li>
                      <li>
                        <svg>
                          <use href="/images/icons.svg#check"></use>
                        </svg>
                        <span>Agent name</span>
                      </li>
                    </ul>
                  </FilterDrop>
                  <Search
                    placeholder="Search agent group... "
                    text={searchAgentG}
                    onChange={val => setSearchAgentG(val)}
                  />
                </div>
              </div>
              {showLocationFilter ? (
                <div className="flex-width-1-2 width-50r less-gp mt-3">
                  <SelectDrop
                    placeholder="Location"
                    type="text"
                    list={list}
                    className="input-height-40"
                  />
                  <SelectDrop
                    placeholder="Total responses"
                    type="text"
                    list={list}
                    className="input-height-40"
                  />
                </div>
              ) : (
                ''
              )}
            </div>

            {agentGroupList && agentGroupList?.agentGroups?.length === 0 && (
              <div className="empty-agent">
                <img src="/images/empty-agent.png" alt="" />
                <p className="mb-2">Add agents group.</p>
              </div>
            )}

            <ul className="grid mostly-4-fill mt-3">
              {agentGroupList &&
                agentGroupList?.agentGroups?.map((agentGroup, i) => {
                  return (
                    <AgentGroupCard
                      key={i}
                      agentGroup={agentGroup}
                      allAgents={allAgents}
                      getAllNewAgentGroup={getAllNewAgentGroup}
                      updateAgentGroup={updateAgentGroup}
                      deleteAnAgentGroup={deleteAnAgentGroup}
                      addAgentsToAgentGroup={addAgentsToAgentGroup}
                      getAllAgentsInAGroup={getAllAgentsInAGroup}
                      allAgentsInGroup={allAgentsInGroup}
                      removeAgentInGroup={removeAgentInGroup}
                      title={agentGroup?.name}
                      created={`Created ${formatDistanceToNow(
                        new Date(agentGroup?.createdAt),
                        { addSuffix: true }
                      )} Ago by ${agentGroup?.createdBy?.firstName} ${
                        agentGroup?.createdBy?.lastName
                      }`}
                      agentCount={agentGroup?.agents?.length}
                    />
                  );
                })}
            </ul>
            <div style={{ marginTop: '3rem' }}>
              <Pagination className="d-flx-alc">
                <IconButton onclick={() => previousPage()} svg="arrow-left" />
                <InputWOLabel disabled placeholder="0" value={currentPage} />
                <span>/</span>
                <span>{Math.ceil(agentGroupList?.count / 20)}</span>
                <IconButton svg="arrow-right" onclick={() => nextPage()} />
              </Pagination>
            </div>
          </>
        )}
      </div>
    </>
  );
};

const mapStateToProps = state => ({
  allAgents: state.agents.allAgents,
  agentGroups: state.agents.allNewAgentsGroup,
  allAgentsInGroup: state.agents.agentsInAGroup,
  searchResult: state.agents.searchedAgent,
  searchedAgentGroupResult: state.agents.searchedAgentGroup,
});

export default connect(mapStateToProps, {
  addAgents,
  getAllAgents,
  deleteAnAgent,
  disableAgent,
  searchAgent,
  getAllNewAgentGroup,
  searchAgentGroup,
  updateAgentGroup,
  deleteAnAgentGroup,
  addAgentsToAgentGroup,
  getAllAgentsInAGroup,
  removeAgentInGroup,
})(AgentMembers);

const AgentsList = styled.ul`
  margin-top: 3rem;
  .agent-list {
    position: relative;
    background: #ffffff;
    border: 1px solid #e8edff;
    border-radius: 12px;
    margin-bottom: 2rem;
  }
`;
const Pagination = styled.div`
  .input-wrapper {
    margin-bottom: 0 !important;
    max-width: 55px;
    .input {
      padding: 1rem;
    }
    input {
      text-align: center;
    }
    .label {
      padding: 0;
      margin: 0;
    }
  }
  span {
    margin: 0 0.5rem;
    font-family: var(--ff-medium);
    font-size: 1.6rem;
  }
`;
