import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { PrimaryIconButton } from '../../components/common/buttons/IconButton';
import {
  DeleteButton,
  NofillButton,
  PrimaryButton,
} from '../../components/common/buttons/PrimaryBtn';
import { ModalWrapper } from '../modals/ModalWrapper.modal';
import { useToasts } from 'react-toast-notifications';
import { TextInput } from '../../components/common/inputs/TextInput';
import { useCopyClipboard } from 'react-recipes';

const PluginApi = ({
  generateApiKey,
  getApiKeys,
  apiKey,
  deleteApiKey,
  resetApiKey,
}) => {
  const [generateAPI, setgenerateAPI] = useState(false);
  const [loading, setIsLoading] = useState(false);
  const [copyKey, setCopyKey] = useCopyClipboard();

  // const [key, setKey] = useState(apiKey?.key)

  const onCopyKey = value => {
    setCopyKey(value);
    addToast('Api key copied', { appearance: 'info' });
    return copyKey;
  };

  const { addToast } = useToasts();

  const key = apiKey?.key;

  useEffect(() => {
    const fetchApiKey = async () => {
      const { data, success } = await getApiKeys();
      if (success) {
        return data;
      }
    };
    fetchApiKey();
  }, [getApiKeys]);

  const generateKey = async () => {
    setIsLoading(true);
    const { generate } = await generateApiKey();
    if (generate?.success) {
      getApiKeys();
      setIsLoading(false);
      addToast('API Key has been created successfully', {
        appearance: 'success',
      });
    } else {
      setIsLoading(false);
      addToast('Key already exist for this workspace', { appearance: 'error' });
      setgenerateAPI(false);
    }
  };

  const onDeleteApiKey = async () => {
    const deleteData = await deleteApiKey();
    if (deleteData?.success) {
      getApiKeys();
      addToast('ApiKey deleted successfully', { appearance: 'success' });
    } else {
      addToast('Could not delete', { appearance: 'error' });
    }
  };

  const onResetApiKey = async () => {
    setIsLoading(true);
    const reset = await resetApiKey();
    if (reset?.success) {
      getApiKeys();
      setIsLoading(false);
      addToast('Your API Key has been reset', { appearance: 'success' });
      setgenerateAPI(false);
    } else {
      setIsLoading(false);
      setgenerateAPI(false);
    }
  };

  return (
    <Section>
      <h3>API Query</h3>
      <p>Reset or copy access token for a more dynamic access to your data.</p>
      <div className="pt-2">
        <TextInput
          label="Private Key"
          readOnly
          value={key}
          type="text"
          placeholder="djfh"
        />
        <div className="flx-jsb-rm">
          <div>
            {key ? (
              <PrimaryButton
                text="Reset Api Keys"
                onclick={() => setgenerateAPI(true)}
              />
            ) : (
              <PrimaryButton
                text="Generate ApiKey"
                loading={loading}
                onclick={() => generateKey()}
              />
            )}

            <ModalWrapper
              visible={generateAPI}
              setvisible={setgenerateAPI}
              title="Generating new API Keys"
              height="390"
            >
              <div className="modal-body">
                <p className="error-info">Important notice</p>
                <p className="warning-text mb-2">
                  If you’ve integrated your present API Keys, you would be
                  required to update the keys with the ones you are about to
                  reset. Are you sure you want to continue?
                </p>
              </div>
              <div className="d-flx-alc-jfe modal-action-wrap px-4">
                <NofillButton
                  title="Cancel"
                  onclick={() => setgenerateAPI(false)}
                />
                <DeleteButton
                  loading={loading}
                  title="Continue"
                  onclick={() => onResetApiKey()}
                />
              </div>
            </ModalWrapper>
          </div>
          <div className="d-flx-alc">
            <PrimaryIconButton
              svg="copy-link-alt"
              onclick={() => onCopyKey(key)}
              title="Copy Link"
              className="co-primary mr-2"
            />
            <PrimaryIconButton
              svg="delete-alt"
              title="Delete"
              className="co-error"
              onclick={() => onDeleteApiKey()}
            />
          </div>
        </div>
      </div>
    </Section>
  );
};
export default PluginApi;

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