import React, { useState, useEffect, useRef } from 'react';
import { useClickAway } from 'react-use';
import { connect } from 'react-redux';
import { useToasts } from 'react-toast-notifications';
import styled from 'styled-components';

import {
  LargeModal,
  ModalWrapper,
  SmallModal,
} from '../../containers/modals/ModalWrapper.modal';
import {
  addFormToFolder,
  deleteFolder,
  getAllFolders,
  renameFolder,
  searchForms,
  getAllForms,
  setActiveFolder,
} from '../../redux/action-creators/form-actions/forms.actions';
import {
  NofillButton,
  NofillButtonsm,
  PrimaryButton,
  DeleteButton,
} from '../common/buttons/PrimaryBtn';
import {
  CustomCheckboxWlabel,
  CustomCheckWHeading,
} from '../common/inputs/Checkbox';
import { CustomSearch } from '../common/inputs/Search';

import { RegularInput } from '../common/inputs/TextInput';
import { FolderActions } from '../dropdowns/DropWIcon';

const FolderCard = ({
  title,
  renameFolder,
  folder,
  getAllFolders,
  deleteFolder,
  allForms,
  searchForms,
  addFormToFolder,
  getAllForms,
  openMenu,
  onOpenMenu,
  setActiveFolder,
  onGetAllForms,
}) => {
  const [deleteModal, setdeleteModal] = useState(false);
  const [selectedForms, setSelected] = useState([]);
  const { addToast } = useToasts();
  const [renameModal, setrenameModal] = useState(false);
  const [saving, setSaving] = useState(false);
  const [addFormToModal, setAddFormToModal] = useState(false);
  const [folderName, setFolderName] = useState('');
  const [allSelected, setAllSelected] = useState(false);
  const [addingForm, setAddingForm] = useState(false);
  const folderMenuRef = useRef(null);
  useClickAway(folderMenuRef, () => {
    if (openMenu === folder._id) {
      onOpenMenu('');
    }
  });

  const onRenameFolder = async () => {
    setSaving(true);
    if (folderName.length > 0) {
      const payload = { name: folderName };
      const response = await renameFolder(folder._id, payload);
      if (response?.success) {
        addToast('Folder name changed', { appearance: 'success' });
        getAllFolders();
        setSaving(false);
        setrenameModal(false);
      } else {
        addToast(response?.error, { appearance: 'error' });
      }
    }
    setSaving(false);
  };

  const onDeleteFolder = async () => {
    setSaving(true);
    const response = await deleteFolder(folder._id);
    if (response?.success) {
      getAllFolders();
      addToast('Folder deleted successfully', { appearance: 'success' });
      setSaving(false);
      setdeleteModal(false);
    } else {
      addToast(response?.error, { appearance: 'error' });
    }
    setSaving(false);
  };

  useEffect(() => {
    setFolderName(folder.name);
  }, []);

  const onSelectForm = id => {
    const copySelectedForm = [...selectedForms];
    if (copySelectedForm.includes(id)) {
      const filterForms = copySelectedForm.filter(item => item !== id);
      setSelected(filterForms);
    } else {
      copySelectedForm.push(id);
      setSelected(copySelectedForm);
    }
  };

  const onSelectAll = () => {
    const tempAllSelected = [];
    if (!allSelected) {
      if (allForms && allForms.forms) {
        allForms.forms.map(form => {
          tempAllSelected.push(form._id);
        });
      }
      setSelected(tempAllSelected);
    } else {
      setSelected([]);
    }
    setAllSelected(!allSelected);
  };

  const onAddFormToFolder = async () => {
    setAddingForm(true);
    if (selectedForms.length > 0) {
      const details = { forms: selectedForms };
      const response = await addFormToFolder(folder._id, details);
      if (response?.success) {
        addToast(response?.message, { appearance: 'success' });
        getAllForms('null');
        setAddFormToModal(false);
        setAddingForm(false);
      } else {
        addToast(response?.error, { appearance: 'error' });
      }
    } else {
      addToast('Select at least one form', { appearance: 'warning' });
    }
    setAddingForm(false);
  };

  const onSetActiveFolder = folderId => {
    onGetAllForms(folderId._id);
    setActiveFolder(folderId);
  };

  return (
    <Card ref={folderMenuRef} className="d-flx-alc-jsb">
      <div
        onClick={() => onSetActiveFolder(folder)}
        className="d-flx-alc cont-wrapper"
      >
        <img src="/images/folder.png" alt="folder" />
        <h4 style={{ cursor: 'pointer' }} className="card-title">
          {title}
        </h4>
      </div>
      <FolderActions
        openMenu={openMenu}
        id={folder._id}
        onOpenMenu={onOpenMenu}
      >
        <div>
          <ul className="drop-list">
            <li
              className="drop-list-item"
              onClick={() => setAddFormToModal(true)}
            >
              <svg>
                <use href="/images/icons.svg#add-form"></use>
              </svg>
              <span>Add a Form</span>
            </li>
            <li className="drop-list-item" onClick={() => setrenameModal(true)}>
              <svg>
                <use href="/images/icons.svg#rename"></use>
              </svg>
              <span>Rename Folder</span>
            </li>
            <li
              className="drop-list-item border-top"
              onClick={() => setdeleteModal(true)}
            >
              <svg>
                <use href="/images/icons.svg#delete"></use>
              </svg>
              <span>Delete</span>
            </li>
          </ul>
          <LargeModal
            visible={addFormToModal}
            setvisible={setAddFormToModal}
            title="Select form to add to folder"
            height={650}
          >
            <div className="px-4 border-bottom pb-3">
              <CustomSearch
                onchange={val => searchForms(val)}
                placeholder="Search form"
                className="bg-grey full-width"
              />
            </div>
            <div className="modal-body py-1 ">
              <ul className="modal-oveflow-wrap alt-350">
                {allForms?.forms?.map((form, i) => {
                  return (
                    <li key={i} className="border-bottom">
                      <CustomCheckWHeading
                        onchange={() => onSelectForm(form._id)}
                        type="checkbox"
                        checked={selectedForms.includes(form._id)}
                        title={form.name}
                        responseCount={form.analytics?.questionCount}
                        category="agents"
                        className="py-2"
                      />
                    </li>
                  );
                })}
              </ul>
            </div>
            <div className="d-flx-alc-jsb alt-modal-footer border-top">
              <CustomCheckboxWlabel
                onchange={() => onSelectAll()}
                type="checkbox"
                label="Select all forms"
              />
              <div className="d-flx-alc modal-action-wrap px-0">
                <NofillButton
                  title="Cancel"
                  onclick={() => setAddFormToModal(false)}
                />
                <PrimaryButton
                  text={
                    addingForm
                      ? 'Saving...'
                      : `${selectedForms.length > 1 ? 'Add forms' : 'Add form'}`
                  }
                  onclick={() => onAddFormToFolder()}
                />
              </div>
            </div>
          </LargeModal>
          <ModalWrapper
            visible={renameModal}
            setvisible={setrenameModal}
            title="Rename folder"
            height={290}
          >
            <div className="modal-body">
              <RegularInput
                type="text"
                value={folderName}
                onchange={val => setFolderName(val)}
                label="Folder name"
                placeholder="Enter new folder name"
              />
            </div>
            <div className="d-flx-alc-jfe modal-action-wrap">
              <NofillButton
                title="cancel"
                onclick={() => setrenameModal(false)}
              />
              <PrimaryButton
                text={saving ? 'Saving...' : 'Rename folder'}
                onclick={() => onRenameFolder()}
              />
            </div>
          </ModalWrapper>
          <SmallModal
            visible={deleteModal}
            setvisible={setdeleteModal}
            title="You’re about to delete a folder"
            height={260}
          >
            <div className="px-4">
              <p>
                You’ll loose everything on this folder, including{' '}
                <span>all forms</span>.
              </p>
            </div>
            <div className="d-flx-alc-jfe modal-action-wrap">
              <NofillButtonsm
                title="No, I’ll pass"
                onclick={() => setdeleteModal(false)}
              />
              <DeleteButton
                title={saving ? 'Deleting...' : 'Delete'}
                onclick={() => onDeleteFolder()}
              />
            </div>
          </SmallModal>
        </div>
      </FolderActions>
    </Card>
  );
};

const mapStateToProps = state => ({
  allForms: state.forms.allForms,
});

export default connect(mapStateToProps, {
  renameFolder,
  getAllFolders,
  deleteFolder,
  searchForms,
  addFormToFolder,
  getAllForms,
  setActiveFolder,
})(FolderCard);

const Card = styled.li`
  background: #ffffff;
  border: 1px solid #e8edff;
  border-radius: 8px;
  padding: 0 1.8rem;
  transition: box-shadow 0.3s ease;
  display: flex;
  cursor: pointer;
  align-items: center;
  .cont-wrapper {
    padding: 1.1rem 0;
  }

  &:hover {
    box-shadow: 0px 10px 70px rgba(224, 228, 237, 0.7);
  }
  img {
    width: 35px;
    height: 30px;
  }
  h4 {
    font-family: var(--ff-medium);
    font-weight: 500;
    font-size: 1.4rem;
    margin-left: 1rem;
    &:first-letter {
      text-transform: uppercase;
    }
  }
`;
