import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { TextInput } from '../../components/common/inputs/TextInput';
import {
  DeleteButton,
  NofillButton,
  NofillButtonsm,
  PrimaryButton,
} from '../../components/common/buttons/PrimaryBtn';
import {
  LargeModal,
  ModalWrapper,
  SmallModal,
} from '../modals/ModalWrapper.modal';
import { LinkPrimaryOutline } from '../../components/common/link-items/PrimaryLink';
import { useToasts } from 'react-toast-notifications';
import { AvatarWTextCheckboxStatus } from '../../components/common/avatars/AvatarWText';
import { DropWMoreIcons } from '../../components/dropdowns/DropWIcon';
import { PrimaryIconButton } from '../../components/common/buttons/IconButton';
import { useCopyClipboard } from 'react-recipes';

const PluginWebhook = ({
  createWebhook,
  getWebhookUrl,
  formPreview,
  webhookUrl,
  removeWebhook,
  updateWebhookUrl,
}) => {
  const [generateAPI, setgenerateAPI] = useState(false);
  const [loading, setIsLoading] = useState(false);

  const [editModal, seteditModal] = useState(false);
  const [deleteModal, setdeleteModal] = useState(false);

  const { addToast } = useToasts();

  const [url, setUrl] = useState('https://  ');
  const [pushConfig, setPushConfig] = useState([]);

  const [copyLink, setCopyLink] = useCopyClipboard();

  const createWebhookIntegration = async () => {
    setIsLoading(true);
    const webhookDetails = {
      url: url,
      pushConfig: [pushConfig],
    };
    const create = await createWebhook(formPreview?._id, webhookDetails);
    if (create?.success) {
      getWebhookUrl(formPreview?._id);
      setgenerateAPI(false);
      setIsLoading(false);
      setUrl('');
      addToast('Webhook created successfully', { appearance: 'success' });
    } else {
      setIsLoading(false);
      setgenerateAPI(false);
    }
  };
  const updateWebhook = async () => {
    setIsLoading(true);
    getWebhookUrl(formPreview?._id);
    const webhookDetails = {
      url,
      pushConfig: [],
    };
    const update = await updateWebhookUrl(formPreview?._id, webhookDetails);
    if (update?.success) {
      // getWebhookUrl(formPreview?._id);
      setIsLoading(false);
      addToast('Webhook created successfully', { appearance: 'success' });
      setgenerateAPI(false);
    } else {
      setIsLoading(false);
      setgenerateAPI(false);
    }
  };

  const deleteWebhook = async () => {
    setIsLoading(true);
    const deleteData = await removeWebhook(formPreview?._id);
    if (deleteData?.success) {
      getWebhookUrl(formPreview?._id);
      addToast('Webhook deleted successfully', { appearance: 'success' });
      setdeleteModal(false);
    } else {
      addToast('webhook hasnt been configured for this form', {
        appearance: 'error',
      });

      setIsLoading(false);
      setdeleteModal(false);
    }
  };

  const onCopyHook = value => {
    setCopyLink(value);
    addToast('Sharable link copied', { appearance: 'info' });
    return copyLink;
  };

  useEffect(() => {
    const fetchWebhook = async () => {
      const { data, success } = await getWebhookUrl(formPreview?._id);
      if (success) {
        setUrl(data.url);
        setPushConfig(data.pushConfig);
      }
    };
    fetchWebhook();
  }, [getWebhookUrl]);

  return (
    <Section>
      <div className="d-flx-jsb">
        <div>
          <h3>Webhooks</h3>
          <p>
            Reset or copy access token for a more dynamic access to your data.
          </p>
        </div>
        <div>
          {webhookUrl?.isConfigured === false ? (
            <PrimaryButton
              text="Configure Webhook"
              onclick={() => setgenerateAPI(true)}
            />
          ) : (
            ''
          )}

          <ModalWrapper
            visible={generateAPI}
            setvisible={setgenerateAPI}
            title="Create webhook"
            height="450"
          >
            <div className="modal-body">
              <TextInput
                type="url"
                placeholder="Enter url"
                name="url"
                value={url}
                onchange={e => setUrl(e.target.value)}
                label="URL"
              />
              <RadioWrapper>
                <p>Configuration Status</p>
                <AvatarWTextCheckboxStatus
                  type="checkbox"
                  className="uk-checkbox"
                  checked={pushConfig === 'pending'}
                  onChange={() => setPushConfig('pending')}
                  value="pending"
                  name="pending"
                  title="pending"
                />
                <AvatarWTextCheckboxStatus
                  type="checkbox"
                  className="uk-checkbox"
                  checked={pushConfig === 'rejected'}
                  onChange={() => setPushConfig('rejected')}
                  value="rejected"
                  name="rejected"
                  title="rejected"
                />
                <AvatarWTextCheckboxStatus
                  type="checkbox"
                  className="uk-checkbox"
                  checked={pushConfig === 'accepted'}
                  onChange={() => setPushConfig('accepted')}
                  value="accepted"
                  name="accepted"
                  title="accepted"
                />
              </RadioWrapper>
            </div>
            <div className="d-flx-alc-jfe modal-action-wrap px-4">
              <NofillButton
                title="Cancel"
                onclick={() => setgenerateAPI(false)}
              />
              <PrimaryButton
                loading={loading}
                onclick={() => createWebhookIntegration()}
                text="Configure Webhook"
              />
            </div>
          </ModalWrapper>
        </div>
      </div>

      {webhookUrl?.isConfigured === false ? (
        <div className="empty-state">
          <h3>Start creating your own app</h3>
          <p className="mb-2">
            Use our APIs to build an app that makes your life better.
          </p>
          <LinkPrimaryOutline
            as="button"
            title="Create webhook"
            onclick={() => setgenerateAPI(true)}
          />
        </div>
      ) : (
        <ul className="grid mostly-4-fill mt-3">
          <Card className="wrapper-deco">
            <div className="d-flx-jsb">
              <h4>Webhook URL</h4>
              <DropWMoreIcons>
                <ul className="drop-list">
                  <li
                    className="drop-list-item co-error"
                    onClick={() => seteditModal(true)}
                  >
                    <svg>
                      <use href="/images/icons.svg#rename"></use>
                    </svg>
                    <span onClick={() => updateWebhook()}>Edit Webhook</span>
                  </li>
                  <li
                    className="drop-list-item co-error"
                    onClick={() => setdeleteModal(true)}
                  >
                    <svg>
                      <use href="/images/icons.svg#delete"></use>
                    </svg>
                    <span>Delete</span>
                  </li>
                </ul>
              </DropWMoreIcons>
            </div>
            <div className="d-flx-alc-jsb mt-1">
              <p className="url-link">{webhookUrl?.url}</p>
              {/* <BasicSwitch title="On"/> */}

              <PrimaryIconButton
                onclick={() => onCopyHook(webhookUrl?.url)}
                svg="copy-link-alt"
                title="Copy Link"
                className="co-primary mr-2"
              />
            </div>

            <LargeModal
              visible={editModal}
              setvisible={seteditModal}
              title="Settings"
              height={556}
            >
              <div className="modal-body">
                <TextInput
                  label="Agent Group name"
                  placeholder="Enter your group name"
                  value={url}
                />
                {/* <TextInput label="Agent Group name" placeholder="Enter your group name"/> */}
                {/* <PasswordInput label="Secret Key" placeholder="Enter your secret key" type="password" /> */}
                <RadioWrapper>
                  <p>Configuration Status</p>
                  <AvatarWTextCheckboxStatus
                    type="checkbox"
                    className="uk-checkbox"
                    checked={pushConfig === 'pending'}
                    onChange={() => setPushConfig('pending')}
                    value="pending"
                    name="pending"
                    title="pending"
                  />
                  <AvatarWTextCheckboxStatus
                    type="checkbox"
                    className="uk-checkbox"
                    checked={pushConfig === 'rejected'}
                    onChange={() => setPushConfig('rejected')}
                    value="rejected"
                    name="rejected"
                    title="rejected"
                  />
                  <AvatarWTextCheckboxStatus
                    type="checkbox"
                    className="uk-checkbox"
                    checked={pushConfig === 'accepted'}
                    onChange={() => setPushConfig('accepted')}
                    value="accepted"
                    name="accepted"
                    title="accepted"
                  />
                </RadioWrapper>
              </div>
              <div className="d-flx-alc-jfe modal-action-wrap">
                <NofillButton
                  title="cancel"
                  onclick={() => seteditModal(false)}
                />
                <PrimaryButton
                  text="Save Changes"
                  loading={loading}
                  onclick={updateWebhook}
                />
              </div>
            </LargeModal>

            <SmallModal
              visible={deleteModal}
              setvisible={setdeleteModal}
              title="You’re about to delete a webhook"
            >
              <div className="px-4">
                <p>
                  You will no longer <span>receive </span> data from Useforms.
                </p>
              </div>
              <div className="d-flx-alc-jfe modal-action-wrap">
                <NofillButtonsm
                  title="No, I’ll pass"
                  onclick={() => setdeleteModal(false)}
                />
                <DeleteButton title="Delete" onclick={deleteWebhook} />
              </div>
            </SmallModal>
          </Card>
        </ul>
      )}
    </Section>
  );
};

export default PluginWebhook;
const Section = styled.section`
  .modal-body {
    padding-top: 0;
  }
  .error-info {
    display: inline-block;
    padding: 0.2rem 2rem;
    background: #ffe6ec;
    border-radius: 4px;
    color: var(--co-error);
    font-family: var(--ff-sbold);
    font-weight: 600;
    font-size: 1.6rem;
    margin-bottom: 2.2rem;
  }
  .warning-text {
    font-size: 1.6rem;
  }
  .modal-action-wrap {
    .btn:last-child {
      padding: 1.4rem 3.2rem;
    }
  }
`;

const RadioWrapper = styled.div`
  p {
    font-size: 14px;
    margin-bottom: 0.4rem;
  }
  label {
    span {
      padding: 0.7rem 4.5rem;
    }
  }
`;
const Card = styled.div`
  padding: 2rem 2.4rem;

  h4 {
    font-weight: 500;
    font-size: 1.6rem;
    font-family: var(--ff-medium);
    color: #1b215c;
  }
  .url-link {
    max-width: 184px;
    word-break: break-word;
  }
  .small-modal {
    p {
      margin-bottom: 0;
    }
  }
`;
