import React, { useState, useRef } from 'react';
import { Link } from 'react-router-dom';
import { useClickAway } from 'react-use';
import { useToasts } from 'react-toast-notifications';
import styled from 'styled-components';
import {
  LargeModal,
  ModalWrapper,
  SmallModal,
} from '../../containers/modals/ModalWrapper.modal';
import InviteFormUser from '../../pages/form-builder/InviteFormUser';
import { IconButton, IconTxtButton } from '../common/buttons/IconButton';
import {
  DeleteButton,
  NofillButton,
  NofillButtonsm,
  PrimaryButton,
} from '../common/buttons/PrimaryBtn';
import {
  SelectFolderOption,
  SelectTemplateCategory,
} from '../common/inputs/Select';
import { RegularInput } from '../common/inputs/TextInput';

export const DropWIcons = () => {
  const [drop, setdrop] = useState(false);
  return (
    <DropDown className="dropdown">
      <IconButton
        svg="more"
        onclick={() => setdrop(!drop)}
        className="btnicon"
      />
      <div className={`drop-wrapper ${drop ? 'active' : ''}`}>
        <ul className="drop-list">
          <li className="drop-list-item">
            <svg>
              <use href="/images/icons.svg#add-to-folder"></use>
            </svg>
            <span>Add to folder</span>
          </li>
          <li className="drop-list-item">
            <svg>
              <use href="/images/icons.svg#rename"></use>
            </svg>
            <span>Rename</span>
          </li>
          <li className="drop-list-item">
            <svg>
              <use href="/images/icons.svg#view"></use>
            </svg>
            <span>View</span>
          </li>
          <li className="drop-list-item">
            <svg>
              <use href="/images/icons.svg#add-collab"></use>
            </svg>
            <span>Add Collaborators</span>
          </li>
          <li className="drop-list-item">
            <svg>
              <use href="/images/icons.svg#make-template"></use>
            </svg>
            <span>Make a Template</span>
          </li>
          <li className="drop-list-item">
            <svg>
              <use href="/images/icons.svg#responses"></use>
            </svg>
            <span>Responses</span>
          </li>
          <li className="drop-list-item">
            <svg>
              <use href="/images/icons.svg#delete"></use>
            </svg>
            <span>Delete</span>
          </li>
        </ul>
      </div>
    </DropDown>
  );
};

export const FormCardActions = ({
  openMenu,
  openedAction,
  id,
  form,
  selectedFolder,
  allFolders,
  setSelectedFolder,
  loading,
  onMoveFormToFolder,
  formName,
  setFormName,
  onUpdateForm,
  getFormUsers,
  templateName,
  setTemplateName,
  templateCategory,
  setTemplateCategory,
  categoryOptions,
  onCreateTemplate,
  deleteForm,
  activeFolder,
  getAllForms,
  history,
}) => {
  const [openFolderModal, setOpenFolderModal] = useState(false);
  const [openRenameModal, setOpenRenameModal] = useState(false);
  const [templateModal, settemplateModal] = useState(false);
  const [deleteModal, setdeleteModal] = useState(false);
  const [addColab, setaddColab] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const { addToast } = useToasts();

  const onDeleteForm = async formId => {
    setDeleting(true);
    const res = await deleteForm(formId);
    if (res && res.success) {
      addToast('Form deleted successfully', { appearance: 'success' });
      getAllForms(activeFolder);
    } else {
      addToast(res?.error, { appearance: 'success' });
    }
    setDeleting(false);
  };

  return (
    <DropDown className="dropdown">
      <IconButton svg="more" onclick={() => openMenu(id)} className="btnicon" />
      <div className={`drop-wrapper ${openedAction === id ? 'active' : ''}`}>
        <ul className="drop-list">
          <li
            onClick={() => setOpenFolderModal(true)}
            className="drop-list-item"
          >
            <svg>
              <use href="/images/icons.svg#add-to-folder"></use>
            </svg>
            <span>Add to folder</span>
          </li>
          <ModalWrapper
            visible={openFolderModal}
            setvisible={setOpenFolderModal}
            title="Add form to a folder"
            height={306}
          >
            <div className="modal-body">
              <div style={{ paddingBottom: '3rem' }}>
                <IconTxtButton title="Create New Group" svg="folder-group" />
              </div>
              <SelectFolderOption
                type="text"
                value={selectedFolder}
                list={allFolders?.folders}
                onchange={folder => setSelectedFolder(folder)}
                placeholder="Select folder"
                label="Folder"
              />
            </div>

            <div className="d-flx-alc-jfe modal-action-wrap modal-footer">
              <NofillButton
                title="Cancel"
                onclick={() => setOpenFolderModal(false)}
              />
              <PrimaryButton
                onclick={async () => {
                  const res = await onMoveFormToFolder();
                  if (res?.success) {
                    setOpenFolderModal(false);
                  }
                }}
                text={loading ? 'processing' : 'Move to folder'}
              />
            </div>
          </ModalWrapper>
          <li
            onClick={() => setOpenRenameModal(true)}
            className="drop-list-item"
          >
            <svg>
              <use href="/images/icons.svg#rename"></use>
            </svg>
            <span>Rename</span>
          </li>
          <ModalWrapper
            visible={openRenameModal}
            setvisible={setOpenRenameModal}
            title="Rename form"
            height={306}
          >
            <div className="modal-body">
              <RegularInput
                value={formName}
                onchange={val => setFormName(val)}
                placeholder="Form name"
              />
            </div>

            <div className="d-flx-alc-jfe modal-action-wrap modal-footer">
              <NofillButton
                title="Cancel"
                onclick={() => setOpenRenameModal(false)}
              />
              <PrimaryButton
                onclick={async () => {
                  const res = await onUpdateForm();
                  if (res?.success) {
                    setOpenRenameModal(false);
                  }
                }}
                text={loading ? 'processing' : 'Rename form'}
              />
            </div>
          </ModalWrapper>
          <li className="drop-list-item">
            <svg>
              <use href="/images/icons.svg#view"></use>
            </svg>
            <Link
              style={{ textDecoration: 'none', color: 'unset' }}
              to={`/builder/${form._id}`}
            >
              <span>View</span>
            </Link>
          </li>
          <li
            onClick={() => {
              getFormUsers(form?._id);
              setaddColab(true);
            }}
            className="drop-list-item"
          >
            <svg>
              <use href="/images/icons.svg#add-collab"></use>
            </svg>
            <span>Add Collaborators</span>
          </li>
          <LargeModal
            visible={addColab}
            setvisible={setaddColab}
            title="Bring colleagues onboard"
            height={650}
          >
            <InviteFormUser formId={form._id} setvisible={setaddColab} />
          </LargeModal>
          <li onClick={() => settemplateModal(true)} className="drop-list-item">
            <svg>
              <use href="/images/icons.svg#make-template"></use>
            </svg>
            <span>Make a Template</span>
          </li>
          <ModalWrapper
            visible={templateModal}
            setvisible={settemplateModal}
            title="Make this form a template"
            height={344}
          >
            <div className="modal-body">
              <RegularInput
                type="text"
                value={templateName}
                placeholder="Enter your template name"
                label="Template name"
                onchange={val => setTemplateName(val)}
              />
              <SelectTemplateCategory
                type="text"
                placeholder="Select category"
                label="Category"
                list={categoryOptions}
                onchange={setTemplateCategory}
                value={templateCategory}
              />
            </div>
            <div className="d-flx-alc-jfe modal-action-wrap">
              <NofillButton
                title="Cancel"
                onclick={() => settemplateModal(false)}
              />
              <PrimaryButton
                onclick={async () => {
                  const res = await onCreateTemplate();
                  if (res?.success) {
                    settemplateModal(false);
                  }
                }}
                text={loading ? 'Creating...' : 'Create Template'}
              />
            </div>
          </ModalWrapper>
          <li
            onClick={() => {
              history.push({
                pathname: `/builder/${form._id}`,
                state: 'results',
              });
            }}
            className="drop-list-item"
          >
            <svg>
              <use href="/images/icons.svg#responses"></use>
            </svg>
            <span>Responses</span>
          </li>
          <li className="drop-list-item">
            <svg>
              <use href="/images/icons.svg#delete"></use>
            </svg>
            <span onClick={() => setdeleteModal(true)}>Delete</span>
            <SmallModal
              visible={deleteModal}
              setvisible={setdeleteModal}
              title="You’re about to delete a form"
            >
              <div className="px-4">
                <p>
                  Are you sure you want to delete
                  <span>{form?.name}</span>.
                </p>
              </div>
              <div className="d-flx-alc-jfe modal-action-wrap">
                <NofillButtonsm
                  title="No, I’ll pass"
                  onclick={() => setdeleteModal(false)}
                />
                <span>
                  <DeleteButton
                    onclick={() => onDeleteForm(form._id)}
                    title={deleting ? 'Deleting...' : 'Delete'}
                  />
                </span>
              </div>
            </SmallModal>
          </li>
        </ul>
      </div>
    </DropDown>
  );
};

export const FolderActions = ({ children, openMenu, onOpenMenu, id }) => {
  return (
    <DropDown className="dropdown">
      <IconButton
        svg="more"
        onclick={() => onOpenMenu(id)}
        className="btnicon"
      />
      <div className={`drop-wrapper ${openMenu === id ? 'active' : ''}`}>
        {children}
      </div>
    </DropDown>
  );
};

export const DropWMoreIcons = ({ children, index, activeIndex }) => {
  const [drop, setdrop] = useState(false);
  const dropRef = useRef(null);
  useClickAway(dropRef, () => {
    setdrop(false);
  });
  return (
    <DropDown ref={dropRef} className="dropdown">
      <IconButton
        svg="more"
        onclick={() => setdrop(!drop)}
        className="btnicon"
      />
      <div
        className={`drop-wrapper ${
          drop && index === activeIndex ? 'active' : ''
        }`}
      >
        {children}
      </div>
    </DropDown>
  );
};

export const DropWMoreHIcons = ({ children }) => {
  const [drop, setdrop] = useState(false);
  return (
    <DropDown className="dropdown">
      <IconButton
        svg="more-h"
        onclick={() => setdrop(!drop)}
        className="btnicon"
      />
      <div className={`drop-wrapper ${drop ? 'active' : ''}`}>{children}</div>
    </DropDown>
  );
};

export const CustomDropWMoreHIcons = ({
  children,
  id,
  setActiveMenu,
  activeMenu,
  workspaceId,
}) => {
  const handleClick = id => {
    const parentEl = document.querySelector(`#${id}`);
    const dropWrap = parentEl.querySelector('.drop-wrapper');
    dropWrap.style.top =
      parentEl.offsetTop - parentEl.parentElement.scrollTop + 'px';
    dropWrap.style.left = Math.round(parentEl.parentElement.offsetWidth) + 'px';
  };
  return (
    <DropDown className="dropdown" id={id}>
      <IconButton
        svg="more-h"
        onclick={() => {
          handleClick(id);
          if (activeMenu !== workspaceId) {
            setActiveMenu(workspaceId);
          } else {
            setActiveMenu('');
          }
        }}
        className="btnicon"
      />
      <div
        onClick={() => {}}
        className={`drop-wrapper ${activeMenu === workspaceId ? 'active' : ''}`}
      >
        {children}
      </div>
    </DropDown>
  );
};

export const DropWMoreHIconsWId = ({ children, id }) => {
  const [drop, setdrop] = useState(false);
  const handleClick = id => {
    const parentEl = document.querySelector(`#${id}`);
    const dropWrap = parentEl.querySelector('.drop-wrapper');
    dropWrap.style.top =
      parentEl.offsetTop - parentEl.parentElement.scrollTop + 'px';
    dropWrap.style.left = Math.round(parentEl.parentElement.offsetWidth) + 'px';
    setdrop(!drop);
  };
  return (
    <DropDown className="dropdown" id={id}>
      <IconButton
        svg="more-h"
        onclick={() => handleClick(id)}
        className="btnicon"
      />
      <div
        onClick={() => {}}
        className={`drop-wrapper ${drop ? 'active' : ''}`}
      >
        {children}
      </div>
    </DropDown>
  );
};

const DropDown = styled.div`
  position: relative;
  .btnicon {
    svg {
      width: 20px !important;
      height: 20px !important;
    }
  }
  .drop-wrapper {
    position: absolute;
    ${'' /* visibility: hidden; */}
    display: none;
    box-shadow: var(--shadow);
    width: 208px;
    border-radius: 8px;
    background: #fff;
    right: 0;
    top: 100%;
    z-index: 6;
    &.active {
      display: block;
    }
  }

  .drop-list {
    padding: 1rem 0;
    .drop-list-item {
      display: flex;
      align-items: center;
      font-family: var(--ff-medium);
      font-size: var(--font-14);
      color: var(--co-body);
      padding: 0.6rem 1.5rem;
      text-transform: none;
      cursor: pointer;
      svg {
        min-width: 32px;
        max-width: 32px;
        width: 32px;
        height: 32px;
      }
      span {
        margin-left: 1rem;
        &:first-letter {
          text-transform: uppercase;
        }
      }
      &:last-child {
        border-top: 1px solid #e8edff;
        color: #d53232;
      }
      &:hover {
        color: var(--co-primary);
      }
    }
  }
`;
