import React, { useEffect, useState } from "react";

import { logger } from "../../../services/monitoring";
import {
  CertificateProvider,
  useCertificateContext,
} from "../../Contexts/CertificateContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import CreateForm from "./CreateForm";
import DownloadCerts from "./DownloadCerts";

const VIEW_FORM = 0;
const VIEW_DOWNLOAD = 1;

const MainForm = () => {
  const { busy, createCert } = useCertificateContext();
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();
  const [view, setView] = useState(VIEW_FORM);
  const [pubCert, setPubCert] = useState(null);
  const [privCert, setPrivCert] = useState(null);
  const [commonName, setCommonName] = useState(null);

  useEffect(() => {
    setTitle("Create Certificate");
    setSitePath([
      {
        label: "Tools",
        link: "/tools/certificates/add",
      },
      {
        label: "Create Certificate",
      },
    ]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const onCreate = async (data) => {
    try {
      const result = await createCert(data, token);
      const name = data.common_name || data.tool_id;

      setCommonName(name);
      setPubCert(result.public_key);
      setPrivCert(result.private_key);
      setMessage(`Created ${name} certificate`);
      setView(VIEW_DOWNLOAD);
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };

  const onChangeView = () => {
    setPubCert(null);
    setPrivCert(null);
    setCommonName(null);

    setView(VIEW_FORM);
  };

  if (view === VIEW_DOWNLOAD)
    return (
      <DownloadCerts
        commonName={commonName}
        publicCert={pubCert}
        privateCert={privCert}
        onChangeView={onChangeView}
      />
    );

  return <CreateForm onCreate={onCreate} busy={busy} />;
};

const CertificateCreate = () => (
  <CertificateProvider>
    <MainForm />
  </CertificateProvider>
);

export default CertificateCreate;
