import React, { useState } from 'react';
import { Link, NavLink } from 'react-router-dom';
import { useToasts } from 'react-toast-notifications';
import ReactTooltip from 'react-tooltip';
import styled from 'styled-components';
import { Avatar, FormUserAvatar } from '../../components/common/avatars/Avatar';

import {
  IconTxtButton,
  MoreDropButton,
  RoundIconButton,
  PrimaryIconButton,
  IconButton,
} from '../../components/common/buttons/IconButton';
import {
  NofillButton,
  PrimaryButton,
} from '../../components/common/buttons/PrimaryBtn';
import { SelectTemplateCategory } from '../../components/common/inputs/Select';

import {
  RegularInput,
  RegularTextArea,
} from '../../components/common/inputs/TextInput';
import { SingleProfileDrop } from '../../components/dropdowns/NavDrop';
import FormSettingsModal from '../../components/form-builder/FormSettingsModal';
import InviteFormUser from '../../pages/form-builder/InviteFormUser';
import { getNameInitials, nameShortner } from '../../utils/helpers';
import { LargeModal, ModalWrapper } from '../modals/ModalWrapper.modal';
import { FormBuilderNavigation } from './Navigation';

export const FormBuilderNav = ({
  formName,
  formId,
  description,
  onUpdateForm,
  updating,
  editFormDescription,
  editFormName,
  updatingForm,
  userProfile,
}) => {
  const [showProfile, setShowProfile] = useState(false);
  const [renameModal, setRenameModal] = useState(false);
  const [shareModal, setShareModal] = useState(false);

  return (
    <>
      <Header>
        <div className="first-child">
          <Link to="/" className="back-link">
            <svg>
              <use href="/images/icons.svg#logo"></use>
            </svg>
            <span>Back to Forms</span>
          </Link>
        </div>
        <div className="center-child">
          <MoreDropButton
            title={nameShortner(formName, 15)}
            svg="drop"
            onclick={() => {
              setRenameModal(true);
            }}
            color="#61677C"
          />
          <ModalWrapper
            visible={renameModal}
            setvisible={setRenameModal}
            title="Save your form"
            height={468}
            width={515}
          >
            <div className="modal-body">
              <RegularInput
                value={formName}
                onchange={value => editFormName(value)}
                label="form name"
                placeholder="Enter your form name"
              />
              <RegularTextArea
                label="Form Description"
                value={description}
                onchange={value => editFormDescription(value)}
                placeholder="Enter your form description"
              />
            </div>
            <div className="d-flx-alc-jfe modal-action-wrap">
              <NofillButton
                title="close"
                onclick={() => setRenameModal(false)}
              />
              <PrimaryButton
                text={updating ? 'saving...' : 'Save Form'}
                onclick={() => onUpdateForm('manual')}
              />
            </div>
          </ModalWrapper>
        </div>
        <div className="last-child">
          <UserNav>
            <Link to={`/preview/${formId}`} target="_blank">
              <PrimaryIconButton
                opt="a"
                title="Preview"
                svg="show"
                color="#61677C"
                className="mr-1 responsive"
              />
            </Link>
            <PrimaryIconButton
              title="Share"
              svg="share"
              color="#61677C"
              className="mr-1 responsive"
              onclick={() => {
                setShareModal(true);
              }}
            />
            <LargeModal
              visible={shareModal}
              setvisible={setShareModal}
              title="Form Settings"
              height={650}
            >
              <FormSettingsModal setShareModal={setShareModal} />
            </LargeModal>
            <PrimaryIconButton
              title={updatingForm ? 'saving...' : 'Save'}
              svg="save"
              color="#61677C"
              className="responsive"
              onclick={() => {
                setRenameModal(true);
              }}
            />
            <SingleProfileDrop
              userProfile={userProfile}
              showProfile={showProfile}
              setShowProfile={setShowProfile}
            />
          </UserNav>
        </div>
      </Header>
    </>
  );
};

export const FormBuilderPageNav = ({
  formUsers,
  bg,
  opt,
  deco,
  formId,
  onDuplicateForm,
  createTemplate,
  categoryOptions,
  activeTab,
  setActiveTab,
  allFolders,
  addFormToFolder,
}) => {
  const [addColab, setaddColab] = useState(false);
  const [settingsModal, setSettingsModal] = useState(false);
  const [templateModal, settemplateModal] = useState(false);
  const [creatingTemplate, setCreatingTemplate] = useState(false);
  const [addToFolderModal, setaddToFolderModal] = useState(false);
  const [templateName, setTemplateName] = useState('');
  const [category, setCategory] = useState({});
  const [folderToAddForm, setFolderToAddForm] = useState({});
  const { addToast } = useToasts();
  const [formAction, setformAction] = useState(false);
  const [loading, setLoading] = useState(false);

  const onCreateTemplate = async () => {
    setCreatingTemplate(true);
    const templateDetails = {
      form: formId,
      category: category._id,
      name: templateName,
    };
    const templateData = await createTemplate(templateDetails);
    if (templateData?.success) {
      addToast('Template created successfully', { appearance: 'success' });
      settemplateModal(false);
      setCreatingTemplate(false);
    } else {
      addToast(templateData?.error, { appearance: 'error' });
      setCreatingTemplate(false);
    }
  };

  const onAddFormToFolder = async () => {
    setLoading(true);
    const details = { forms: [formId] };
    const res = await addFormToFolder(folderToAddForm._id, details);
    if (res?.success) {
      addToast('Form added to folder', { appearance: 'success' });
      setaddToFolderModal(false);
    } else {
      addToast(res?.error, { appearance: 'error' });
    }
    setLoading(false);
  };

  return (
    <React.Fragment>
      <Header as={opt} bg={bg} deco={deco}>
        <div className="first-child">
          <IconButton
            svg="more-h"
            className="toggle-btn"
            onclick={() => setformAction(!formAction)}
          />
          <div className={`form-actions ${formAction ? 'active' : ''}`}>
            <div>
              <ReactTooltip id="addToFolder" />
              <span data-for="addToFolder" data-tip="Add to a folder">
                <RoundIconButton
                  bg="rgba(0, 75, 255, 0.1)"
                  svg="folder"
                  onclick={() => setaddToFolderModal(true)}
                />
              </span>
              <ModalWrapper
                visible={addToFolderModal}
                setvisible={setaddToFolderModal}
                title="Add form to a folder"
                height={306}
              >
                <div className="modal-body">
                  <SelectTemplateCategory
                    type="text"
                    placeholder="Select folder"
                    label="Folder"
                    list={allFolders?.folders}
                    value={folderToAddForm}
                    onchange={setFolderToAddForm}
                  />
                </div>
                <div className="d-flx-alc-jsb modal-action-wrap modal-footer">
                  <IconTxtButton title="Create New Folder" svg="folder-group" />
                  <PrimaryButton
                    onclick={onAddFormToFolder}
                    text={loading ? 'Loading...' : 'Move to folder'}
                  />
                </div>
              </ModalWrapper>
            </div>
            <ReactTooltip id="duplicateForm" />

            <span
              data-for="duplicateForm"
              data-tip="Duplicate form"
              onClick={() => onDuplicateForm()}
            >
              <RoundIconButton bg="rgba(0, 75, 255, 0.1)" svg="duplicate" />
            </span>
            <div>
              <ReactTooltip id="createTemplate" />
              <span data-for="createTemplate" data-tip="Create template">
                <RoundIconButton
                  bg="rgba(0, 75, 255, 0.1)"
                  svg="template"
                  onclick={() => settemplateModal(true)}
                />
              </span>
              <ModalWrapper
                visible={templateModal}
                setvisible={settemplateModal}
                title="Make this form a template"
                height={344}
              >
                <div className="modal-body">
                  <RegularInput
                    type="text"
                    placeholder="Enter your template name"
                    label="Template name"
                    onchange={val => setTemplateName(val)}
                  />
                  <SelectTemplateCategory
                    type="text"
                    placeholder="Select category"
                    label="Category"
                    list={categoryOptions}
                    onchange={setCategory}
                    value={category}
                  />
                </div>
                <div className="d-flx-alc-jfe modal-action-wrap">
                  <NofillButton
                    title="Cancel"
                    onclick={() => settemplateModal(false)}
                  />
                  <PrimaryButton
                    text={creatingTemplate ? 'Creating...' : 'Create Template'}
                    onClick={() => onCreateTemplate()}
                  />
                </div>
              </ModalWrapper>
            </div>

            <ReactTooltip id="Plugins" />
            <span data-for="Plugins" data-tip="Plugins">
              <Link to={`/plugins/${formId}`}>
                <RoundIconButton
                  bg="rgba(0, 75, 255, 0.1)"
                  svg="plugin"
                  // opt="a"
                  // link="/plugins/"
                />
              </Link>
            </span>

            <div>
              <RoundIconButton
                bg="rgba(0, 75, 255, 0.1)"
                svg="settings"
                onclick={() => {
                  setSettingsModal(true);
                }}
              />
              <LargeModal
                visible={settingsModal}
                setvisible={setSettingsModal}
                title="Form Settings"
                height={650}
              >
                <FormSettingsModal setShareModal={setSettingsModal} />
              </LargeModal>
            </div>
          </div>
        </div>
        <div className="center-child alt">
          <FormBuilderNavigation
            setActiveTab={setActiveTab}
            activeTab={activeTab}
          />
        </div>
        <div className="d-flx-alc page-extras last-child form-colab">
          {formUsers && formUsers.users
            ? formUsers.users.map((user, i) => {
                if (i < 3) {
                  return (
                    <FormUserAvatar
                      key={i}
                      image={user.profilePicture ? user.profilePicture : ''}
                      initials={getNameInitials(
                        `${user.firstName} ${user.lastName}`
                      )}
                    />
                  );
                }
              })
            : ''}
          {formUsers && formUsers.users && formUsers.users.length > 3 && (
            <span
              style={{ cursor: 'pointer' }}
              onClick={() => setaddColab(true)}
            >
              <Avatar initials={`+ ${formUsers.users.length - 3}`} />
            </span>
          )}
          <div>
            <ReactTooltip id="addFormUser" />
            <span data-for="delete" data-tip="Invite form collaborators">
              <RoundIconButton svg="plus" onclick={() => setaddColab(true)} />
            </span>
            <LargeModal
              visible={addColab}
              setvisible={setaddColab}
              title="Bring colleagues onboard"
              height={650}
            >
              <InviteFormUser formId={formId} setvisible={setaddColab} />
            </LargeModal>
          </div>
        </div>
      </Header>
    </React.Fragment>
  );
};

export const SettingsNav = () => {
  const [showProfile, setShowProfile] = useState(false);
  return (
    <React.Fragment>
      <Header>
        <Link to="/" className="back-link">
          <svg>
            <use href="/images/icons.svg#logo"></use>
          </svg>
          <span>Back to Forms</span>
        </Link>
        <div className="absolute-center">
          <NavLink to="/profile/">Settings</NavLink>
        </div>
        <UserNav>
          <SingleProfileDrop
            showProfile={showProfile}
            setShowProfile={setShowProfile}
          />
        </UserNav>
      </Header>
    </React.Fragment>
  );
};

const Header = styled.header`
  position: relative;
  background: ${props => (props.bg ? props.bg : ' var(--main-background)')};
  padding: 1rem 2rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: ${props => (props.deco ? props.deco : '')};
  > * {
    flex: 1;
    &.first-child {
    }
    &.center-child {
      display: flex;
      justify-content: center;
      &.alt {
        flex: 3;
        justify-content: flex-start;
        @media (min-width: 768px) {
          flex: 1;
          justify-content: center;
        }
      }
    }
    &.last-child {
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
  &.save-nav {
    padding: 2rem;
  }
  .back-link {
    display: flex;
    align-items: center;
    svg {
      width: 30px;
      height: 36px;
      @media (min-width: 768px) {
        width: 20px;
        height: 26px;
      }
    }
    span {
      font-size: 1.6rem;
      font-weight: 500;
      font-family: var(--ff-medium);
      margin-left: 1.5rem;
      display: none;
      @media (min-width: 768px) {
        display: inline-block;
      }
    }
  }
  .toggle-btn {
    padding-left: 0;
    color: var(--co-head);
    svg {
      width: 25px;
      height: 25px;
    }
    @media (min-width: 768px) {
      display: none;
    }
  }
  .form-actions {
    position: absolute;
    position: absolute;
    display: flex;
    ${'' /* flex-direction: column; */}
    justify-content: space-between;
    width: 0;
    overflow: hidden;
    top: 5px;
    left: 5rem;
    background: #ffffff;
    box-shadow: 0px 10px 70px rgba(224, 228, 237, 0.7);
    transition: all 0.3s ease-in-out;
    z-index: 1;
    border-radius: 4px;
    &.active {
      width: 240px;
      overflow: auto;
      padding: 1rem;
      @media (min-width: 768px) {
        width: auto;
        left: 0;
        padding: 0;
      }
    }
    @media (min-width: 768px) {
      position: relative;
      flex-direction: row;
      align-items: center;
      justify-content: flex-start;
      width: auto;
      top: 0;
      left: 0;
      background: transparent;
      box-shadow: none;
      overflow: auto;
      z-index: auto;
      border-radius: 0;
      > * {
        &:not(:last-child) {
          margin-right: 1rem;
          @media (min-width: 1280px) {
            margin-right: 2.5rem;
          }
        }
      }
    }
  }

  .form-colab {
    display: none;
    @media (min-width: 768px) {
      display: flex;
    }
  }
`;
const UserNav = styled.div`
  display: flex;
  align-items: center;
  .space {
    margin-left: 1rem;
  }
`;
// const Logo = styled.img`
//   height: 20px;
//   @media (min-width: 768px) {
//     height: 26px;
//   }
// `;
