import React, { useState, useEffect, useRef } from 'react';
import { useClickAway } from 'react-use';
import Styled from 'styled-components';
import { Avatar, FormUserAvatar } from '../common/avatars/Avatar';
import { IconButton } from '../common/buttons/IconButton';
import { format } from 'date-fns';
import { getNameInitials, nameShortner } from '../../utils/helpers';
import { FormCardActions } from '../dropdowns/DropWIcon';
import { Link, withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import {
  createTemplate,
  deleteForm,
  getAllForms,
  getFormUsers,
  moveFormToFolder,
  updateForm,
} from '../../redux/action-creators/form-actions/forms.actions';
import { useToasts } from 'react-toast-notifications';

const FormCard = ({
  form,
  openMenu,
  openedAction,
  allFolders,
  moveFormToFolder,
  getAllForms,
  updateForm,
  getFormUsers,
  templateCategories,
  createTemplate,
  deleteForm,
  activeFolder,
  history,
}) => {
  const [selectedFolder, setSelectedFolder] = useState({});
  const [formName, setFormName] = useState('');
  const [loading, setLoading] = useState(false);
  const [templateName, setTemplateName] = useState('');
  const [templateCategory, setTemplateCategory] = useState({});
  const { addToast } = useToasts();
  const formMenuRef = useRef(null);
  useClickAway(formMenuRef, () => {
    if (openedAction === form._id) {
      openMenu('');
    }
  });

  const onMoveFormToFolder = async () => {
    if (Object.keys(selectedFolder).length > 0) {
      setLoading(true);
      const details = {
        forms: [form._id],
      };
      const response = await moveFormToFolder(selectedFolder._id, details);

      if (response.success) {
        addToast('Form added to folder', {
          appearance: 'success',
        });
        setLoading(false);
        getAllForms(activeFolder);
        return response;
      }
    } else {
      addToast('Please select a folder', {
        appearance: 'warning',
      });
    }
  };

  useEffect(() => {
    setFormName(form?.name);
  }, [form]);

  const onUpdateForm = async () => {
    if (formName.length > 0) {
      setLoading(true);
      const details = {
        name: formName,
      };
      const response = await updateForm(details, form._id);

      if (response?.success) {
        getAllForms(activeFolder);
        addToast('Form name update', {
          appearance: 'success',
        });
      } else {
        addToast(response?.error, {
          appearance: 'error',
        });
      }

      setLoading(false);
      return response;
    } else {
      addToast('Please enter form name', {
        appearance: 'warning',
      });
    }
  };

  const onCreateTemplate = async () => {
    setLoading(true);
    const templateDetails = {
      form: form._id,
      category: templateCategory._id,
      name: templateName,
    };
    const templateData = await createTemplate(templateDetails);

    if (templateData?.success) {
      addToast('Template created successfully', {
        appearance: 'success',
      });
      setLoading(false);
      return templateData;
    } else {
      addToast(templateData?.error, {
        appearance: 'error',
      });
      setLoading(false);
    }
  };

  return /*#__PURE__*/ React.createElement(
    Card,
    null,
    /*#__PURE__*/ React.createElement(
      Link,
      {
        to: `/builder/${form._id}`,
      },
      /*#__PURE__*/ React.createElement(
        'div',
        {
          className: `status ${form.status}`,
        },
        /*#__PURE__*/ React.createElement(
          'svg',
          null,
          /*#__PURE__*/ React.createElement('use', {
            href: '/images/icons.svg#calendar',
          })
        ),
        /*#__PURE__*/ React.createElement(
          'span',
          null,
          format(new Date(form?.createdAt), 'd LLL yyyy')
        )
      ),
      /*#__PURE__*/ React.createElement(
        'h4',
        {
          className: 'card-title',
        },
        nameShortner(form.name, 25)
      ),
      /*#__PURE__*/ React.createElement(
        'div',
        {
          className: 'card-details',
        },
        /*#__PURE__*/ React.createElement(
          'p',
          null,
          /*#__PURE__*/ React.createElement(
            'span',
            {
              className: 'info',
            },
            form.analytics ? form.analytics.questionCount : 0
          ),
          /*#__PURE__*/ React.createElement('span', null, 'Questions')
        ),
        /*#__PURE__*/ React.createElement(
          'p',
          null,
          /*#__PURE__*/ React.createElement(
            'span',
            {
              className: 'info',
            },
            form.analytics ? form.analytics.entryCount : 0
          ),
          /*#__PURE__*/ React.createElement('span', null, 'Responses')
        )
      )
    ),
    /*#__PURE__*/ React.createElement(
      'div',
      {
        className: 'card-footer',
      },
      /*#__PURE__*/ React.createElement(
        'div',
        {
          className: 'd-flx-alc page-extras',
        },
        form && form.users
          ? form.users.map((user, i) => {
              if (i < 3) {
                return /*#__PURE__*/ React.createElement(FormUserAvatar, {
                  key: i,
                  image: user.profilePicture ? user.profilePicture : '',
                  initials: getNameInitials(
                    `${user.firstName} ${user.lastName}`
                  ),
                });
              }
            })
          : '',
        form &&
          form.users &&
          form.users.length > 3 &&
          /*#__PURE__*/ React.createElement(
            'span',
            {
              style: {
                cursor: 'pointer',
              },
            },
            /*#__PURE__*/ React.createElement(Avatar, {
              initials: `+ ${form.users.length - 3}`,
            })
          )
      ),
      /*#__PURE__*/ React.createElement(
        'div',
        {
          ref: formMenuRef,
          className: 'd-flx-alc',
        },
        /*#__PURE__*/ React.createElement(IconButton, {
          svg: 'share',
          className: 'btn-icon',
        }),
        /*#__PURE__*/ React.createElement(FormCardActions, {
          id: form._id,
          onMoveFormToFolder: onMoveFormToFolder,
          loading: loading,
          allFolders: allFolders,
          selectedFolder: selectedFolder,
          setSelectedFolder: setSelectedFolder,
          form: form,
          openMenu: openMenu,
          openedAction: openedAction,
          formName: formName,
          setFormName: setFormName,
          onUpdateForm: onUpdateForm,
          getFormUsers: getFormUsers,
          templateName: templateName,
          setTemplateName: setTemplateName,
          templateCategory: templateCategory,
          setTemplateCategory: setTemplateCategory,
          categoryOptions: templateCategories,
          onCreateTemplate: onCreateTemplate,
          deleteForm: deleteForm,
          getAllForms: getAllForms,
          activeFolder: activeFolder,
          history: history,
        })
      )
    )
  );
};

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

export default withRouter(
  connect(mapStateToProps, {
    moveFormToFolder,
    getAllForms,
    updateForm,
    getFormUsers,
    createTemplate,
    deleteForm,
  })(FormCard)
);
const Card = Styled.li`
    background: #FFFFFF;
    border: 1px solid #E8EDFF;
    border-radius: 8px;
    padding: 2.3rem;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    transition: box-shadow 0.3s ease;
    &:hover{
        box-shadow: 0px 10px 70px rgba(224, 228, 237, 0.7);
    }
    a{
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      height: 100%;
    }
    .card-title{
        margin: 2.7rem 0;
        font-family: var(--ff-medium);
        font-weight: 500;
        color: var(--co-body);
        font-size: 1.8rem;

    }
    .card-details{
        display: flex;
        margin-bottom: 2.5rem;
        p{
            padding-right: 3rem;
            font-family: var(--ff-body);
            font-weight: 400;
            .info{
                font-size: 2.4rem;
                font-family: var(--ff-sbold);
                font-weight: 600;
                color: var(--co-head);
                line-height: 1.6;
            }
            span{
                display: block;
                color: var(--co-body);
            }
        }
    }
    .card-footer{
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-top: 1px solid #E8EDFF;
        padding-top: 2rem; 
        .page-extras{
            >*{
              margin-right: 0.5rem;  
            }
        }
        .btn-icon{
            svg{
                width: 14px !important;
                height: 19px !important
            }
        }
    
    }
`;
