import React, { Suspense, useState } from "react";
import "./Setup.scss";
import { Button, Spin, Steps, Form } from "antd";
import SetupService from "../../services/SetupService";

import { useNavigate } from "react-router-dom";
import { LOCAL_STORAGE, SERVICE_RESPONSE } from "../../constants";

const Welcome = React.lazy(() => import("./Welcome"));
const Require = React.lazy(() => import("./Require"));
const DBconnection = React.lazy(() => import("./DBconnection"));
const ZabbixCon = React.lazy(() => import("./ZabbixCon"));
const TLSconnection = React.lazy(() => import("./TLSconnection"));
const Loglocation = React.lazy(() => import("./LogLocation"));
const Summary = React.lazy(() => import("./Summary"));
const Final = React.lazy(() => import("./Final"));

const { Step } = Steps;
const steps = [
  {
    title: "WELCOME",
  },
  {
    title: "Pre-requisites",
  },
  {
    title: "TLS Connection",
  },
  {
    title: "Database connection",
  },
  {
    title: "Zabbix Connection",
  },
  {
    title: "Log Location",
  },
  {
    title: "Summary",
  },
  {
    title: "Finish",
  },
];

const initialValues = {
  DBPort: "0",
  JazDBPort: "0",

  // TLS
  JA_DB_ENCRYPTION: false,
  JA_DB_VERIFY_HOST: false,
  DB_ENCRYPTION: false,
  DB_VERIFY_HOST: false,
  JA_DB_CA_FILE: "",
  JA_DB_KEY_FILE: "",
  JA_DB_CERT_FILE: "",
  JA_DB_CIPHER_LIST: "",
  DB_CA_FILE: "",
  DB_KEY_FILE: "",
  DB_CERT_FILE: "",
  DB_CIPHER_LIST: "",
};

const Setup = () => {
  const navigate = useNavigate();
  let comp = "";
  const [current, setCurrent] = useState(0);
  const [formDataDBTmp, setFormDataDBTmp] = useState();
  const [formDataZabbix, setFormZabbix] = useState();
  const [formDataTLS, setFormTLS] = useState({});
  const [formDataLog, setFormLog] = useState();
  const [isLoading, setIsloading] = useState(false);

  const prev = () => {
    setIsloading(false);
    setCurrent(current - 1);
  };

  const [form] = Form.useForm();

  const handleFinish = (values) => {
    values.DBPort = values.DBPort ?? 0;
    values.JazDBPort = values.JazDBPort ?? 0;
    if (current === 1) {
      if (values.pass === 1) {
        setCurrent(current + 1);
      }
    } else if (current === 2) {
      // TLS step – just store values and move on
      setIsloading(true);
      setFormTLS(values);

      // Skip API if no TLS enabled
      if (!values.JA_DB_ENCRYPTION && !values.DB_ENCRYPTION) {
        setCurrent(current + 1);
        setIsloading(false);
      } else {
        SetupService.getTLSConnection(values)
          .then((result) => {
            const response = result.detail.data;

            if (response.result === "fail" && response.fieldErrors) {
              // Set field-level errors
              const fields = Object.keys(response.fieldErrors).map((key) => ({
                name: key,
                errors: [response.fieldErrors[key]],
              }));
              form.setFields(fields);
            } else {
              setCurrent(current + 1);
            }

            setIsloading(false);
          })
          .catch(() => {
            setIsloading(false);
          });
      }
    } else if (current === 3) {
      setIsloading(true);

      values.DB_ENCRYPTION = formDataTLS["DB_ENCRYPTION"];
      values.DB_CA_FILE = formDataTLS["DB_CA_FILE"];
      values.DB_KEY_FILE = formDataTLS["DB_KEY_FILE"];
      values.DB_CERT_FILE = formDataTLS["DB_CERT_FILE"];
      values.DB_VERIFY_HOST = formDataTLS["DB_VERIFY_HOST"];
      values.DB_CIPHER_LIST = formDataTLS["DB_CIPHER_LIST"];
      values.JA_DB_ENCRYPTION = formDataTLS["JA_DB_ENCRYPTION"];
      values.JA_DB_CA_FILE = formDataTLS["JA_DB_CA_FILE"];
      values.JA_DB_KEY_FILE = formDataTLS["JA_DB_KEY_FILE"];
      values.JA_DB_CERT_FILE = formDataTLS["JA_DB_CERT_FILE"];
      values.JA_DB_VERIFY_HOST = formDataTLS["JA_DB_VERIFY_HOST"];
      values.JA_DB_CIPHER_LIST = formDataTLS["JA_DB_CIPHER_LIST"];
      document.getElementById("dberrmsg").innerHTML = "";
      document.getElementById("dbErr").classList.add("errHide");
      setFormDataDBTmp(values);
      //Check DB connection
      SetupService.getDBConnection(values).then((result) => {
        if (result.detail.message === "success") {
          setCurrent(current + 1);
        } else {
          document.getElementById("dberrmsg").innerHTML =
            "Database cannot be connected";
          document.getElementById("dbErr").style.borderColor = "red";
          // document.getElementById("dbErr").classList.remove("errHide");
        }
        setIsloading(false);
      });
    } else if (current === 4) {
      setIsloading(true);
      document.getElementById("zbxerrmsg").innerHTML = "";
      document.getElementById("zbxErr").classList.add("errHide");
      //   const formDataZbx = new FormData();
      //   formDataZbx.append("zabbixURL", values["zabbixURL"]);
      setFormZabbix(values);
      SetupService.getZbxConnection(values).then((result) => {
        if (result.type == SERVICE_RESPONSE.OK) {
          if (result.detail.message === "version") {
            document.getElementById("zbxerrmsg").innerHTML =
              "Zabbix version incompatible";
            document.getElementById("zbxErr").style.borderColor = "red";
            // document.getElementById("zbxErr").classList.remove("errHide");
          } else {
            setCurrent(current + 1);
          }
        } else {
          document.getElementById("zbxerrmsg").innerHTML =
            "Zabbix cannot be connected";
          document.getElementById("zbxErr").style.borderColor = "red";
          console.log(result.detail.message);
        }
        setIsloading(false);
      });
    } else if (current === 5) {
      setIsloading(true);
      document.getElementById("logerrmsg").innerHTML = "";
      document.getElementById("logErr").classList.add("errHide");
      setFormLog(values);
      var fullLogFile = {
        appLog: "",
      };
      // Linux
      if (values["appLog"].slice(-1) == "/") {
        fullLogFile.appLog = values["appLog"] + "" + values["logfile"];
      } else {
        fullLogFile.appLog = values["appLog"] + "/" + values["logfile"];
      }
      // if (values["appLog"].slice(-1) == "\\") {
      //   fullLogFile.appLog = values["appLog"] + "" + values["logfile"];
      // } else {
      //   fullLogFile.appLog = values["appLog"] + "\\" + values["logfile"];
      // }
      SetupService.getLogPathCheck(fullLogFile).then((result) => {
        let response = result.detail.data;
        if (response.result === "fail") {
          document.getElementById("logerrmsg").innerHTML =
            response.resultMessage;
          document.getElementById("logErr").style.borderColor = "red";
          // document.getElementById("logErr").classList.remove("errHide");
        } else {
          setCurrent(current + 1);
        }
        setIsloading(false);
      });
    } else if (current === 6) {
      setIsloading(true);
      document.getElementById("wserrmsg").innerHTML = "";
      document.getElementById("wsErr").classList.add("errHide");
      const formDataCreate = formDataDBTmp;

      //   for (const key in formDataDBTmp) {
      //     formDataCreate.append(key, formDataDBTmp[key]);
      //   }
      //   formDataCreate.append("zabbixURL", formDataZabbix["zabbixURL"]);
      //   formDataCreate.append("appLog", formDataLog["appLog"]);
      formDataCreate.zabbixURL = formDataZabbix["zabbixURL"];
      formDataCreate.sslVerificationFlag =
        formDataZabbix["sslVerificationFlag"];
      if (formDataLog["appLog"].slice(-1) == "/") {
        formDataCreate.appLog =
          formDataLog["appLog"] + "" + formDataLog["logfile"];
      } else {
        formDataCreate.appLog =
          formDataLog["appLog"] + "/" + formDataLog["logfile"];
      }
      let root = window.location.href;
      //   root = root.substring(0, root.length - 6);
      formDataCreate.HostName = root.substring(0, root.length - 6);

      SetupService.createConfig(formDataCreate).then((result) => {
        let response = result.detail.data;
        if (response.result === "fail") {
          document.getElementById("wserrmsg").innerHTML =
            response.resultMessage;
          document.getElementById("wsErr").style.borderColor = "red";
          // document.getElementById("wsErr").classList.remove("errHide");
        } else {
          localStorage.setItem(
            LOCAL_STORAGE.EXTERNAL_LOGIN_LINK,
            formDataCreate.zabbixURL
          );
          setCurrent(current + 1);
        }
        setIsloading(false);
      });
    } else {
      setCurrent(current + 1);
    }
  };

  function handleKeyUp(event) {
    // Enter
    if (event.keyCode === 13) {
      form.submit();
    }
  }

  return (
    <>
      <div className="full">
        <div className="parent">
          <div className="setupBody">
            <div className="leftContent">
              <Steps Steps progressDot direction="vertical" current={current}>
                {steps.map((item) => (
                  <Step key={item.title} title={item.title} />
                ))}
              </Steps>
            </div>

            <div className="rightContent">
              <Spin size="large" spinning={isLoading}>
                <div className="steps-content">
                  {(() => {
                    switch (current) {
                      case 0:
                        comp = (
                          <Suspense fallback={<Spin size="large" />}>
                            <Welcome
                              form={form}
                              onFinish={handleFinish}
                              onKeyUp={handleKeyUp}
                            />
                          </Suspense>
                        );
                        break;
                      case 1:
                        comp = (
                          <Suspense fallback={<Spin size="large" />}>
                            <Require
                              form={form}
                              onFinish={handleFinish}
                              onKeyUp={handleKeyUp}
                            />
                          </Suspense>
                        );
                        break;
                      case 2:
                        comp = (
                          <Suspense fallback={<Spin size="large" />}>
                            <TLSconnection
                              form={form}
                              onFinish={handleFinish}
                              onKeyUp={handleKeyUp}
                            />
                          </Suspense>
                        );
                        break;
                      case 3:
                        comp = (
                          <Suspense fallback={<Spin size="large" />}>
                            <DBconnection
                              form={form}
                              onFinish={handleFinish}
                              onKeyUp={handleKeyUp}
                              initialValues={initialValues}
                            />
                          </Suspense>
                        );
                        break;
                      case 4:
                        comp = (
                          <Suspense fallback={<Spin size="large" />}>
                            <ZabbixCon
                              form={form}
                              onFinish={handleFinish}
                              onKeyUp={handleKeyUp}
                            />
                          </Suspense>
                        );
                        break;
                      case 5:
                        comp = (
                          <Suspense fallback={<Spin size="large" />}>
                            <Loglocation
                              form={form}
                              onFinish={handleFinish}
                              onKeyUp={handleKeyUp}
                            />
                          </Suspense>
                        );
                        break;
                      case 6:
                        comp = (
                          <Suspense fallback={<Spin size="large" />}>
                            <Summary
                              form={form}
                              dbData={formDataDBTmp}
                              zbxData={formDataZabbix}
                              logData={formDataLog}
                              onKeyUp={handleKeyUp}
                              onFinish={handleFinish}
                            />
                          </Suspense>
                        );
                        break;
                      default:
                        comp = (
                          <Suspense fallback={<Spin size="large" />}>
                            <Final />
                          </Suspense>
                        );
                        break;
                    }
                  })()}
                  {comp}
                </div>
              </Spin>
              <div className="steps-action">
                {current > 0 && (
                  <Button className="prevBtn" onClick={() => prev()}>
                    Previous
                  </Button>
                )}
                {current === steps.length - 1 && (
                  <Button type="primary" onClick={() => navigate("/login")}>
                    Done
                  </Button>
                )}
                {current === steps.length - 2 && (
                  <Button className="createBtn" onClick={() => form.submit()}>
                    Create
                  </Button>
                )}
                {current < steps.length - 2 && (
                  <Button className="nextBtn" onClick={() => form.submit()}>
                    Next
                  </Button>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default Setup;
