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

import { useSMSContext, SMSProvider } from "../../Contexts/SMSContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import { logger } from "../../../services/monitoring";
import SendForm from "./SendForm";
import ViewResult from "./ViewResult";

const VIEW_FORM = 0;
const VIEW_RESULT = 1;

const MainForm = () => {
  const { busy, sendSMS } = useSMSContext();
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();
  const [view, setView] = useState(VIEW_FORM);
  const [result, setResult] = useState(null);

  useEffect(() => {
    setTitle("Send SMS");
    setSitePath([
      {
        label: "Tools",
        link: "/tools/sms/send",
      },
      {
        label: "Send SMS",
      },
    ]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const onSend = async (data) => {
    try {
      setResult(await sendSMS(data, token));

      setMessage(`Sent ${data.messageText} to ${data.ICCID}`);
      setView(VIEW_RESULT);
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };

  const onChangeView = () => {
    setResult(null);

    setView(VIEW_FORM);
  };

  if (view === VIEW_RESULT)
    return <ViewResult result={result} onChangeView={onChangeView} />;

  return <SendForm onSend={onSend} busy={busy} />;
};

const SMSSend = () => (
  <SMSProvider>
    <MainForm />
  </SMSProvider>
);

export default SMSSend;
