import React, { useState } from 'react';
import styled from 'styled-components';
import {
  LargeModal,
  ModalWrapper,
} from '../../containers/modals/ModalWrapper.modal';
import { TextInput } from '../common/inputs/TextInput';
import { Search, SearchInAgentGroup } from '../common/inputs/Search';
import { IconButton, PrimaryIconButton } from '../common/buttons/IconButton';
import {
  DeleteButton,
  NofillButton,
  NofillButtonsm,
  PrimaryButton,
} from '../common/buttons/PrimaryBtn';
import { CheckboxWlabel, CheckboxWOlabel } from '../common/inputs/Checkbox';
import { useToasts } from 'react-toast-notifications';
import {
  AvatarWText,
  AvatarWTextCheckbox,
} from '../common/avatars/AvatarWText';
import { DropWMoreIcons } from '../dropdowns/DropWIcon';
import { getNameInitials } from '../../utils/helpers';
export const AgentGroupCard = ({
  created,
  title,
  agentCount,
  agentGroup,
  updateAgentGroup,
  allAgents,
  getAllNewAgentGroup,
  deleteAnAgentGroup,
  addAgentsToAgentGroup,
  getAllAgentsInAGroup,
  allAgentsInGroup,
  removeAgentInGroup,
}) => {
  const [addAgentModal, setAddAgentModal] = useState(false);
  const [agentsDetailsModal, setagentsDetailsModal] = useState(false);
  const [renameModal, setrenameModal] = useState(false);
  const [deleteModal, setdeleteModal] = useState(false);
  const [saving, setSaving] = useState(false);
  const [agentName, setAgentName] = useState('');
  const [searchText, setSearchText] = useState('');
  const [searchedAgents, setSearchedAgents] = useState([]);
  const [agentsInGroup, addAgentsInGroup] = useState([]); // const [agentToBeRemoved, setAgentToBeRemoved] = 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(agentGroup?._id)) {
      tempSelectedId = agentsInGroup.filter(agentId => {
        return agentId !== agent._id;
      });
      tempSelectedDetails = selectedAgentsDetails.filter(agentId => {
        return agentId._id !== agent._id;
      });
      addAgentsInGroup(tempSelectedId);
      setSelectedAgentsDetails(tempSelectedDetails);
    } else {
      tempSelectedId = [...agentsInGroup];
      tempSelectedDetails = [...selectedAgentsDetails];
      tempSelectedId.push(agent._id);
      tempSelectedDetails.push(agent);
      addAgentsInGroup(tempSelectedId);
      setSelectedAgentsDetails(tempSelectedDetails);
    }
  };

  const onSelectAllAgent = selectAllAgents => {
    let copyAllAgent = [];
    setSelectAllagents(!selectAllAgents);

    if (selectAllAgents === false) {
      allAgents.agents.map(agent => {
        copyAllAgent.push(agent?._id);
      });
      setSelectedAgentsDetails(allAgents?.agents);
      addAgentsInGroup(copyAllAgent);
    } else {
      copyAllAgent = [];
      addAgentsInGroup(copyAllAgent);
      setSelectedAgentsDetails([]);
    }
  };

  const renameAgentGroupName = async () => {
    setSaving(true);
    const newGroupDetails = {
      name: agentName,
    };
    const editGroup = await updateAgentGroup(agentGroup?._id, newGroupDetails);

    if (editGroup?.success) {
      getAllNewAgentGroup();
      setrenameModal(false);
      addToast('Agent group renamed successfully', {
        appearance: 'success',
      });
      setSaving(false);
    } else {
      setSaving(false);
      setrenameModal(false);
    }
  };

  const onDeleteAgentGroup = async () => {
    setSaving(true);
    const deleteData = await deleteAnAgentGroup(agentGroup?._id);

    if (deleteData?.success) {
      getAllNewAgentGroup();
      addToast('Agent Group deleted successfully', {
        appearance: 'success',
      });
      setdeleteModal(false);
    } else {
      setSaving(false);
      setdeleteModal(false);
    }
  };

  const onAddAgentsToAgentGroup = async () => {
    setSaving(true);
    const singleAgent = {
      agents: agentsInGroup,
    };
    const addAgents = await addAgentsToAgentGroup(singleAgent);

    if (addAgents?.success) {
      getAllNewAgentGroup();
      addToast('agent has been added successfully', {
        appearance: 'success',
      });
      setSaving(false);
      setAddAgentModal(false);
    } else {
      setSaving(false);
      setAddAgentModal(false);
    }
  };

  const onRemoveAgentFromGroup = async () => {
    setSaving(true);
    const agentRemoved = {
      agents: [],
    };
    const removedAgent = await removeAgentInGroup(
      agentGroup?._id,
      agentRemoved
    );

    if (removedAgent?.success) {
      // getAllNewAgentGroup();
      addToast('Agent has been removed successfully', {
        appearance: 'success',
      });
      setdeleteModal(false);
      setagentsDetailsModal(false);
    } else {
      setSaving(false);
      setdeleteModal(false);
      setagentsDetailsModal(false);
    }
  };

  const openAgentDetails = () => {
    setagentsDetailsModal(true);
    getAllAgentsInAGroup(agentGroup?._id);
  };

  const performSearch = searchText => {
    const searchedData = allAgentsInGroup?.agents?.filter(ele => {
      const name = ele.email.toLowerCase();
      return name.includes(searchText.toLowerCase());
    });
    setSearchedAgents(searchedData);
    return searchedData;
  };

  const handleChange = e => {
    const searchTerm = e.target.value;
    setSearchText(searchTerm);
    performSearch(searchTerm);
  };

  const agentsInAnAgentGroup = searchText?.length
    ? searchedAgents
    : allAgentsInGroup?.agents;
  return /*#__PURE__*/ React.createElement(
    Card,
    null,
    /*#__PURE__*/ React.createElement(
      'div',
      {
        className: 'card-check',
      },
      /*#__PURE__*/ React.createElement(CheckboxWOlabel, {
        type: 'checkbox',
        name: 'group',
      })
    ),
    /*#__PURE__*/ React.createElement(
      'div',
      {
        className: 'card-body',
        onClick: openAgentDetails,
      },
      /*#__PURE__*/ React.createElement('h4', null, title),
      /*#__PURE__*/ React.createElement('p', null, created)
    ),
    /*#__PURE__*/ React.createElement(
      LargeModal,
      {
        visible: agentsDetailsModal,
        setvisible: setagentsDetailsModal,
        title: `${agentCount} agents`,
        largespantitle: allAgentsInGroup?.name,
        height: 650,
      },
      /*#__PURE__*/ React.createElement(
        'div',
        {
          className: 'px-4 border-bottom',
        },
        /*#__PURE__*/ React.createElement(TextInput, {
          type: 'text',
          value: agentName || allAgentsInGroup?.name,
          onchange: e => setAgentName(e.target.value),
          label: 'Agent Group name',
        })
      ),
      /*#__PURE__*/ React.createElement(
        'div',
        {
          className: 'px-4 border-bottom py-3',
        },
        /*#__PURE__*/ React.createElement(SearchInAgentGroup, {
          placeholder: 'Search agent',
          value: searchText,
          onchange: handleChange,
          className: 'bg-grey full-width',
        }),
        /*#__PURE__*/ React.createElement(PrimaryIconButton, {
          svg: 'plus-round',
          title: 'Add agent',
          onclick: () => setAddAgentModal(true),
          className: 'add-agent-btn mt-1',
        })
      ),
      /*#__PURE__*/ React.createElement(
        'div',
        {
          className: 'modal-body py-1 ',
        },
        /*#__PURE__*/ React.createElement(
          'ul',
          {
            className: 'modal-oveflow-wrap ',
          },
          agentsInAnAgentGroup?.map((item, i) =>
            /*#__PURE__*/ React.createElement(
              'li',
              {
                className: 'py-2 border-bottom d-flx-alc-jsb',
                key: i,
              },
              /*#__PURE__*/ React.createElement(AvatarWText, {
                image: item?.profilePicture,
                initials: getNameInitials(
                  item && item.firstName
                    ? `${item?.firstName} ${item?.lastName}`
                    : 'New User'
                ),
                name:
                  item && item.firstName
                    ? `${item?.firstName} ${item?.lastName}`
                    : 'New User',
                email: item.email,
                category: 'agents',
              }),
              /*#__PURE__*/ React.createElement(
                NofillButton, // loading={saving}
                {
                  onclick: () => onRemoveAgentFromGroup(item?._id),
                  title: 'Remove',
                }
              )
            )
          )
        )
      ),
      /*#__PURE__*/ React.createElement(
        'div',
        {
          className: 'd-flx-alc-jsb alt-modal-footer',
        },
        /*#__PURE__*/ React.createElement(
          'div',
          {
            className: 'd-flx-alc modal-action-wrap px-0',
          },
          /*#__PURE__*/ React.createElement(NofillButton, {
            title: 'Cancel',
            onclick: () => setagentsDetailsModal(false),
          }),
          /*#__PURE__*/ React.createElement(PrimaryButton, {
            text: 'Save changes',
            onclick: renameAgentGroupName,
          })
        )
      )
    ),
    /*#__PURE__*/ React.createElement(
      'div',
      {
        className: 'card-footer',
      },
      /*#__PURE__*/ React.createElement(
        'p',
        {
          className: 'd-flx-alc page-extras',
        },
        agentCount,
        ' agents'
      ),
      /*#__PURE__*/ React.createElement(
        'div',
        {
          className: 'd-flx-alc',
        },
        /*#__PURE__*/ React.createElement(
          'div',
          null,
          /*#__PURE__*/ React.createElement(IconButton, {
            svg: 'agent-group-alt',
            className: 'btn-icon',
            onclick: () => setAddAgentModal(true),
          }),
          /*#__PURE__*/ React.createElement(
            LargeModal,
            {
              visible: addAgentModal,
              setvisible: setAddAgentModal,
              title: 'Add agents',
              spantitle: agentGroup?.name,
              height: 650,
            },
            /*#__PURE__*/ React.createElement(
              'div',
              {
                className: 'px-4 border-bottom pb-2',
              },
              /*#__PURE__*/ React.createElement(Search, {
                placeholder: 'Search agent',
                className: 'bg-grey full-width',
              })
            ),
            /*#__PURE__*/ React.createElement(
              'div',
              {
                className: 'modal-body py-1 ',
              },
              /*#__PURE__*/ React.createElement(
                'ul',
                {
                  className: 'modal-oveflow-wrap',
                },
                allAgents?.agents?.length === 0 &&
                  /*#__PURE__*/ React.createElement(
                    'h5',
                    null,
                    'No agents here at the moment'
                  ),
                allAgents?.agents?.length > 0 &&
                  allAgents?.agents?.map((ag, i) => {
                    return /*#__PURE__*/ React.createElement(
                      'li',
                      {
                        className: 'py-2 border-bottom',
                        key: i,
                      },
                      /*#__PURE__*/ React.createElement(AvatarWTextCheckbox, {
                        type: 'checkbox',
                        image: '/images/avatar1.png',
                        initials: 'ay',
                        name: 'New User',
                        email: ag?.email,
                        category: 'agents',
                        onChange: () => addOrRemoveAgentFromGroup(ag?._id),
                        checked: checkSelected(ag?._id),
                      })
                    );
                  })
              )
            ),
            /*#__PURE__*/ React.createElement(
              'div',
              {
                className: 'd-flx-alc-jsb alt-modal-footer',
              },
              /*#__PURE__*/ React.createElement(CheckboxWlabel, {
                type: 'checkbox',
                checked: selectAllAgents,
                onchange: () => {
                  onSelectAllAgent(selectAllAgents);
                },
                label: 'Select all agents',
              }),
              /*#__PURE__*/ React.createElement(
                'div',
                {
                  className: 'd-flx-alc modal-action-wrap px-0',
                },
                /*#__PURE__*/ React.createElement(NofillButton, {
                  title: 'Cancel',
                  onclick: () => setAddAgentModal(false),
                }),
                /*#__PURE__*/ React.createElement(PrimaryButton, {
                  loading: saving,
                  onclick: () => onAddAgentsToAgentGroup(),
                  text: 'Add Agents',
                })
              )
            )
          )
        ),
        /*#__PURE__*/ React.createElement(
          DropWMoreIcons,
          null,
          /*#__PURE__*/ React.createElement(
            'ul',
            {
              className: 'drop-list',
            },
            /*#__PURE__*/ React.createElement(
              'li',
              {
                className: 'drop-list-item',
                onClick: () => setrenameModal(true),
              },
              /*#__PURE__*/ React.createElement(
                'svg',
                null,
                /*#__PURE__*/ React.createElement('use', {
                  href: '/images/icons.svg#rename',
                })
              ),
              /*#__PURE__*/ React.createElement('span', null, 'Rename group')
            ),
            /*#__PURE__*/ React.createElement(
              'li',
              {
                className: 'drop-list-item border-top',
                onClick: () => setdeleteModal(true),
              },
              /*#__PURE__*/ React.createElement(
                'svg',
                null,
                /*#__PURE__*/ React.createElement('use', {
                  href: '/images/icons.svg#delete',
                })
              ),
              /*#__PURE__*/ React.createElement('span', null, 'Delete')
            )
          ),
          /*#__PURE__*/ React.createElement(
            ModalWrapper,
            {
              visible: renameModal,
              setvisible: setrenameModal,
              title: 'Rename agent group',
              height: 290,
            },
            /*#__PURE__*/ React.createElement(
              'div',
              {
                className: 'modal-body',
              },
              /*#__PURE__*/ React.createElement(TextInput, {
                label: 'Agent Group name',
                name: 'name',
                value: agentName,
                onchange: e => setAgentName(e.target.value),
                placeholder: 'Enter your group name',
              })
            ),
            /*#__PURE__*/ React.createElement(
              'div',
              {
                className: 'd-flx-alc-jfe modal-action-wrap',
              },
              /*#__PURE__*/ React.createElement(NofillButton, {
                title: 'cancel',
                onclick: () => setrenameModal(false),
              }),
              /*#__PURE__*/ React.createElement(PrimaryButton, {
                loading: saving,
                onclick: renameAgentGroupName,
                text: 'Rename group',
              })
            )
          ),
          /*#__PURE__*/ React.createElement(
            ModalWrapper,
            {
              visible: deleteModal,
              setvisible: setdeleteModal,
              title: 'You\u2019re about to delete a group',
            },
            /*#__PURE__*/ React.createElement(
              'div',
              {
                className: 'px-4',
              },
              /*#__PURE__*/ React.createElement(
                'p',
                null,
                'Every ',
                /*#__PURE__*/ React.createElement('span', null, 'agent'),
                ' attached to this group will be renameed to ',
                /*#__PURE__*/ React.createElement('span', null, 'agent list'),
                '.'
              )
            ),
            /*#__PURE__*/ React.createElement(
              'div',
              {
                className: 'd-flx-alc-jfe modal-action-wrap',
              },
              /*#__PURE__*/ React.createElement(NofillButtonsm, {
                title: 'No, I\u2019ll pass',
                onclick: () => setdeleteModal(false),
              }),
              /*#__PURE__*/ React.createElement(DeleteButton, {
                loading: setSaving,
                onclick: () => onDeleteAgentGroup(agentGroup?._id),
                title: 'Delete',
              })
            )
          )
        )
      )
    )
  );
};
export const AgentGroupCardWOActions = ({ created, title, agentCount }) => {
  return /*#__PURE__*/ React.createElement(
    Card,
    null,
    /*#__PURE__*/ React.createElement(
      'div',
      {
        className: 'card-check',
      },
      /*#__PURE__*/ React.createElement(CheckboxWOlabel, {
        type: 'checkbox',
        name: 'group',
      })
    ),
    /*#__PURE__*/ React.createElement(
      'div',
      {
        className: 'card-body',
      },
      /*#__PURE__*/ React.createElement('h4', null, title),
      /*#__PURE__*/ React.createElement('p', null, created)
    ),
    /*#__PURE__*/ React.createElement(
      'div',
      {
        className: 'card-footer',
      },
      /*#__PURE__*/ React.createElement('p', null, agentCount, ' agents')
    )
  );
};
const Card = styled.li`
  background: #ffffff;
  border: 1px solid #e8edff;
  border-radius: 8px;
  padding: 2.3rem 1.5rem;
  transition: box-shadow 0.3s ease;
  position: relative;
  &:hover {
    box-shadow: 0px 10px 70px rgba(224, 228, 237, 0.7);
  }
  .card-check {
    position: absolute;
    right: 1.5rem;
    top: 3rem;
  }
  .card-body {
    padding-bottom: 3rem;
    h4 {
      max-width: 170px;
      margin-bottom: 2.7rem;
      font-family: var(--ff-medium);
      font-weight: 500;
      color: var(--co-body);
      font-size: 1.8rem;
    }
    p {
      font-size: 1.2rem;
    }
  }

  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1px solid #e8edff;
    padding-top: 1.5rem;
  }
  .full-width {
    max-width: 100%;
    background: #f6f8ff;
    border: 1px solid #e8edff;
  }
  .add-agent-btn {
    svg {
      width: 24px;
      height: 24px;
      margin-right: 1rem;
      color: var(--co-primary);
    }
  }
`;
