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 /*#__PURE__*/ React.createElement(
    Section,
    null,
    /*#__PURE__*/ React.createElement(
      'div',
      {
        className: 'd-flx-jsb',
      },
      /*#__PURE__*/ React.createElement(
        'div',
        null,
        /*#__PURE__*/ React.createElement('h3', null, 'Webhooks'),
        /*#__PURE__*/ React.createElement(
          'p',
          null,
          'Reset or copy access token for a more dynamic access to your data.'
        )
      ),
      /*#__PURE__*/ React.createElement(
        'div',
        null,
        webhookUrl?.isConfigured === false
          ? /*#__PURE__*/ React.createElement(PrimaryButton, {
              text: 'Configure Webhook',
              onclick: () => setgenerateAPI(true),
            })
          : '',
        /*#__PURE__*/ React.createElement(
          ModalWrapper,
          {
            visible: generateAPI,
            setvisible: setgenerateAPI,
            title: 'Create webhook',
            height: '450',
          },
          /*#__PURE__*/ React.createElement(
            'div',
            {
              className: 'modal-body',
            },
            /*#__PURE__*/ React.createElement(TextInput, {
              type: 'url',
              placeholder: 'Enter url',
              name: 'url',
              value: url,
              onchange: e => setUrl(e.target.value),
              label: 'URL',
            }),
            /*#__PURE__*/ React.createElement(
              RadioWrapper,
              null,
              /*#__PURE__*/ React.createElement(
                'p',
                null,
                'Configuration Status'
              ),
              /*#__PURE__*/ React.createElement(AvatarWTextCheckboxStatus, {
                type: 'checkbox',
                className: 'uk-checkbox',
                checked: pushConfig === 'pending',
                onChange: () => setPushConfig('pending'),
                value: 'pending',
                name: 'pending',
                title: 'pending',
              }),
              /*#__PURE__*/ React.createElement(AvatarWTextCheckboxStatus, {
                type: 'checkbox',
                className: 'uk-checkbox',
                checked: pushConfig === 'rejected',
                onChange: () => setPushConfig('rejected'),
                value: 'rejected',
                name: 'rejected',
                title: 'rejected',
              }),
              /*#__PURE__*/ React.createElement(AvatarWTextCheckboxStatus, {
                type: 'checkbox',
                className: 'uk-checkbox',
                checked: pushConfig === 'accepted',
                onChange: () => setPushConfig('accepted'),
                value: 'accepted',
                name: 'accepted',
                title: 'accepted',
              })
            )
          ),
          /*#__PURE__*/ React.createElement(
            'div',
            {
              className: 'd-flx-alc-jfe modal-action-wrap px-4',
            },
            /*#__PURE__*/ React.createElement(NofillButton, {
              title: 'Cancel',
              onclick: () => setgenerateAPI(false),
            }),
            /*#__PURE__*/ React.createElement(PrimaryButton, {
              loading: loading,
              onclick: () => createWebhookIntegration(),
              text: 'Configure Webhook',
            })
          )
        )
      )
    ),
    webhookUrl?.isConfigured === false
      ? /*#__PURE__*/ React.createElement(
          'div',
          {
            className: 'empty-state',
          },
          /*#__PURE__*/ React.createElement(
            'h3',
            null,
            'Start creating your own app'
          ),
          /*#__PURE__*/ React.createElement(
            'p',
            {
              className: 'mb-2',
            },
            'Use our APIs to build an app that makes your life better.'
          ),
          /*#__PURE__*/ React.createElement(LinkPrimaryOutline, {
            as: 'button',
            title: 'Create webhook',
            onclick: () => setgenerateAPI(true),
          })
        )
      : /*#__PURE__*/ React.createElement(
          'ul',
          {
            className: 'grid mostly-4-fill mt-3',
          },
          /*#__PURE__*/ React.createElement(
            Card,
            {
              className: 'wrapper-deco',
            },
            /*#__PURE__*/ React.createElement(
              'div',
              {
                className: 'd-flx-jsb',
              },
              /*#__PURE__*/ React.createElement('h4', null, 'Webhook URL'),
              /*#__PURE__*/ React.createElement(
                DropWMoreIcons,
                null,
                /*#__PURE__*/ React.createElement(
                  'ul',
                  {
                    className: 'drop-list',
                  },
                  /*#__PURE__*/ React.createElement(
                    'li',
                    {
                      className: 'drop-list-item co-error',
                      onClick: () => seteditModal(true),
                    },
                    /*#__PURE__*/ React.createElement(
                      'svg',
                      null,
                      /*#__PURE__*/ React.createElement('use', {
                        href: '/images/icons.svg#rename',
                      })
                    ),
                    /*#__PURE__*/ React.createElement(
                      'span',
                      {
                        onClick: () => updateWebhook(),
                      },
                      'Edit Webhook'
                    )
                  ),
                  /*#__PURE__*/ React.createElement(
                    'li',
                    {
                      className: 'drop-list-item co-error',
                      onClick: () => setdeleteModal(true),
                    },
                    /*#__PURE__*/ React.createElement(
                      'svg',
                      null,
                      /*#__PURE__*/ React.createElement('use', {
                        href: '/images/icons.svg#delete',
                      })
                    ),
                    /*#__PURE__*/ React.createElement('span', null, 'Delete')
                  )
                )
              )
            ),
            /*#__PURE__*/ React.createElement(
              'div',
              {
                className: 'd-flx-alc-jsb mt-1',
              },
              /*#__PURE__*/ React.createElement(
                'p',
                {
                  className: 'url-link',
                },
                webhookUrl?.url
              ),
              /*#__PURE__*/ React.createElement(PrimaryIconButton, {
                onclick: () => onCopyHook(webhookUrl?.url),
                svg: 'copy-link-alt',
                title: 'Copy Link',
                className: 'co-primary mr-2',
              })
            ),
            /*#__PURE__*/ React.createElement(
              LargeModal,
              {
                visible: editModal,
                setvisible: seteditModal,
                title: 'Settings',
                height: 556,
              },
              /*#__PURE__*/ React.createElement(
                'div',
                {
                  className: 'modal-body',
                },
                /*#__PURE__*/ React.createElement(TextInput, {
                  label: 'Agent Group name',
                  placeholder: 'Enter your group name',
                  value: url,
                }),
                /*#__PURE__*/ React.createElement(
                  RadioWrapper,
                  null,
                  /*#__PURE__*/ React.createElement(
                    'p',
                    null,
                    'Configuration Status'
                  ),
                  /*#__PURE__*/ React.createElement(AvatarWTextCheckboxStatus, {
                    type: 'checkbox',
                    className: 'uk-checkbox',
                    checked: pushConfig === 'pending',
                    onChange: () => setPushConfig('pending'),
                    value: 'pending',
                    name: 'pending',
                    title: 'pending',
                  }),
                  /*#__PURE__*/ React.createElement(AvatarWTextCheckboxStatus, {
                    type: 'checkbox',
                    className: 'uk-checkbox',
                    checked: pushConfig === 'rejected',
                    onChange: () => setPushConfig('rejected'),
                    value: 'rejected',
                    name: 'rejected',
                    title: 'rejected',
                  }),
                  /*#__PURE__*/ React.createElement(AvatarWTextCheckboxStatus, {
                    type: 'checkbox',
                    className: 'uk-checkbox',
                    checked: pushConfig === 'accepted',
                    onChange: () => setPushConfig('accepted'),
                    value: 'accepted',
                    name: 'accepted',
                    title: 'accepted',
                  })
                )
              ),
              /*#__PURE__*/ React.createElement(
                'div',
                {
                  className: 'd-flx-alc-jfe modal-action-wrap',
                },
                /*#__PURE__*/ React.createElement(NofillButton, {
                  title: 'cancel',
                  onclick: () => seteditModal(false),
                }),
                /*#__PURE__*/ React.createElement(PrimaryButton, {
                  text: 'Save Changes',
                  loading: loading,
                  onclick: updateWebhook,
                })
              )
            ),
            /*#__PURE__*/ React.createElement(
              SmallModal,
              {
                visible: deleteModal,
                setvisible: setdeleteModal,
                title: 'You\u2019re about to delete a webhook',
              },
              /*#__PURE__*/ React.createElement(
                'div',
                {
                  className: 'px-4',
                },
                /*#__PURE__*/ React.createElement(
                  'p',
                  null,
                  'You will no longer ',
                  /*#__PURE__*/ React.createElement('span', null, 'receive '),
                  ' data from Useforms.'
                )
              ),
              /*#__PURE__*/ React.createElement(
                'div',
                {
                  className: 'd-flx-alc-jfe modal-action-wrap',
                },
                /*#__PURE__*/ React.createElement(NofillButtonsm, {
                  title: 'No, I\u2019ll pass',
                  onclick: () => setdeleteModal(false),
                }),
                /*#__PURE__*/ React.createElement(DeleteButton, {
                  title: 'Delete',
                  onclick: deleteWebhook,
                })
              )
            )
          )
        )
  );
};

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;
    }
  }
`;
