import React, { useCallback, useEffect, useRef, useState } from "react";
import { LazyLoad } from "@/components/LazyLoad";
import { GlobalContext, Views } from "@/context/Global";
import { StringCaser } from "@/utils/utils";
import { MkdButton } from "@/components/MkdButton";
import { WorkflowTypes } from "@/utils/constants";
import { CustomCodeConfig } from "../CustomCodeConfig";
import { DBQueryConfig } from "../DBQueryConfig";
import { VariableConfig } from "../VariableConfig";
import { HttpRequestConfig } from "../HttpRequestConfig";
import { SuccessResponseConfig } from "../SuccessResponseConfig";
import { ErrorResponseConfig } from "../ErrorResponseConfig";
import { ModalSidebar } from "@/components/ModalSidebar";
import { MkdControlledInput } from "@/components/MkdControlledInput";

const WorkflowWrapperModal = ({
  open,
  onToggleModal,
  parentId,
  workflow,
  segment,
  addVariable,
  variables,
  updateWorkflow,
}) => {
  const {
    dispatch: globalDispatch,
    state: { selectedRoute, view },
  } = React.useContext(GlobalContext);

  const [name, setName] = useState("");
  const [data, setData] = useState(null);

  // Ref to keep track of previous open state
  const prevOpenRef = useRef(open);

  const onSetData = useCallback(
    (field, value) => {
      let tempData = JSON.parse(JSON.stringify({ ...data }));

      tempData = {
        ...tempData,
        [field]: value,
      };
      setData(() => ({ ...tempData }));
    },
    [data]
  );

  const onSaveTrigger = useCallback(() => {
    updateWorkflow(workflow?.id, data, parentId, segment);
    console.log("saving");
  }, [data, updateWorkflow, workflow?.id, parentId, segment]);

  useEffect(() => {
    onSetData("action_name", name);
  }, [name]);

  useEffect(() => {
    if (workflow) {
      setData(() => ({ ...workflow }));
      setName(workflow?.action_name);
    }
  }, [workflow]);

  useEffect(() => {
    if (prevOpenRef.current && !open) {
      onSaveTrigger();
    }
    // Update ref to current open state
    prevOpenRef.current = open;
  }, [open, onSaveTrigger]);

  return (
    <>
      <ModalSidebar
        isModalActive={open}
        customMinWidthInTw="min-w-[50%] max-w-[50%] w-[50%]"
        closeModalFn={() => onToggleModal(false)}
        showHeader
        title={StringCaser(workflow?.name, {
          casetype: "capitalize",
          separator: " ",
        })}
        headerContent={
          <div className="flex w-full justify-end gap-3">
            <button
              onClick={() => {
                onToggleModal(false);
              }}
            >
              Cancel
            </button>
            {/* <MkdButton onClick={onSaveTrigger} showPlus={false}>
              Save
            </MkdButton> */}
          </div>
        }
      >
        <div className="flex h-fit w-full flex-col items-start justify-start px-5 ">
          {workflow?.name === WorkflowTypes.SuccessResponse &&
          view === Views.BasicRouteEditor ? null : (
            <LazyLoad>
              <MkdControlledInput
                label={"Action Name"}
                onChange={(e) => setName(e.target.value)}
                value={name}
                placeholder={`Action Name`}
              />
            </LazyLoad>
          )}

          <div
            className={`w-full ${
              workflow?.name === WorkflowTypes.CustomCode
                ? "overflow-hidden"
                : ""
            } pb-10`}
          >
            <LazyLoad count={3}>
              {workflow?.name === WorkflowTypes.DBQuery ? (
                <DBQueryConfig
                  segment={segment}
                  parentId={parentId}
                  addVariable={addVariable}
                  workflow={workflow}
                  variables={variables}
                  onSetData={onSetData}
                />
              ) : null}
              {workflow?.name === WorkflowTypes.CustomCode ? (
                <CustomCodeConfig
                  title={"Code"}
                  segment={segment}
                  parentId={parentId}
                  workflow={workflow}
                  onSetData={onSetData}
                  variables={variables}
                />
              ) : null}
              {workflow?.name === WorkflowTypes.HttpRequest ? (
                <HttpRequestConfig
                  segment={segment}
                  parentId={parentId}
                  addVariable={addVariable}
                  workflow={workflow}
                  variables={variables}
                  onSetData={onSetData}
                />
              ) : null}
              {workflow?.name === WorkflowTypes.SuccessResponse ? (
                <SuccessResponseConfig
                  segment={segment}
                  parentId={parentId}
                  addVariable={addVariable}
                  workflow={workflow}
                  variables={variables}
                  onSetData={onSetData}
                  open={open}
                />
              ) : null}
              {workflow?.name === WorkflowTypes.ErrorResponse ? (
                <ErrorResponseConfig
                  segment={segment}
                  parentId={parentId}
                  addVariable={addVariable}
                  workflow={workflow}
                  variables={variables}
                  onSetData={onSetData}
                />
              ) : null}
              {workflow?.name === WorkflowTypes.Variables ? (
                <VariableConfig
                  segment={segment}
                  parentId={parentId}
                  addVariable={addVariable}
                  workflow={workflow}
                  variables={variables}
                  onSetData={onSetData}
                />
              ) : null}
            </LazyLoad>
          </div>
        </div>
      </ModalSidebar>
    </>
  );
};

export default WorkflowWrapperModal;
