import React, { useEffect, useState } from "react";
import { LazyLoad } from "@/components/LazyLoad";
import { GlobalContext, Views, setGLobalProperty } from "@/context/Global";
import { CodeEditor } from "@/components/CodeEditor";
import { DropdownVariables } from "@/components/DropdownVariables";
import {
  buildWorkflowCode,
  getAPITopTemplate,
  getAPIBottomTemplate,
} from "@/utils/options/DataTypes";
import { InteractiveButton } from "@/components/InteractiveButton";
import { ModalSidebar } from "@/components/ModalSidebar";

const RouteLogic = ({ variables }) => {
  const {
    dispatch: globalDispatch,
    state: { selectedRoute, view, route_logic, custom_code },
  } = React.useContext(GlobalContext);
  const [code, setCode] = useState("");
  const [topTemplate, setTopTemplate] = useState("");
  const [bottomTemplate, setBottomTemplate] = useState("");
  const [mainCode, setMainCode] = useState("");
  // const [isChanged, setIsChanged] = useState(false);

  const extractGeneratedCode = (codeTemplate, startFixedPart, endFixedPart) => {
    if (!codeTemplate) return "";
    const parts = codeTemplate.split(startFixedPart);
    if (parts.length < 2) return "";
    const endParts = parts[1].split(endFixedPart);
    return endParts[0]?.trim() || "";
  }

  const buildWorkflow = (prev_code) => {
    const [tempTopTemplate, codeContent, tempBottomTemplate] =
      buildWorkflowCode(selectedRoute, "Route Logic", prev_code);

    const existingCode = extractGeneratedCode(selectedRoute?.code, tempTopTemplate, tempBottomTemplate);

    let newCode = "";
    if (custom_code?.length > 0) {
      newCode = custom_code;
    } else if (existingCode?.length > 0) {
      newCode = existingCode;
    } else {
      newCode = codeContent || "";
    }

    setCode(newCode);
    setTopTemplate(tempTopTemplate);
    setBottomTemplate(tempBottomTemplate);
    setMainCode([tempTopTemplate, newCode, tempBottomTemplate].join("\n"));
  };

  useEffect(() => {
    if(selectedRoute?.id) {
      buildWorkflow(custom_code);
    }
  }, [selectedRoute?.id, custom_code]);

  useEffect(() => {
    if (code && code !== "" && code !== "//======") {
      const tempMainCode = [topTemplate, code, bottomTemplate].join("\n");
      const data = {
        ...selectedRoute,
        code: tempMainCode,
        logic: code.split("//======")[1] || code,
      };
      setGLobalProperty(globalDispatch, data, "selectedRoute", "RouteLogic 1");
    }
    // setIsChanged((prev)=> !prev);
  }, [code, topTemplate, bottomTemplate]);

  return (
    <LazyLoad>
      <ModalSidebar
        isModalActive={route_logic}
        customMinWidthInTw="min-w-[50%] max-w-[50%] w-[50%]"
        closeModalFn={() =>
          setGLobalProperty(globalDispatch, false, "route_logic")
        }
        showHeader
        title={"Preview API"}
      >
        <LazyLoad>
          <div className="relative my-5 px-4">
            <div className={`mb-5 flex w-full items-center justify-end gap-3`}>
              {view === Views.BasicRouteEditor ? null : (
                <LazyLoad>
                  {/* <InteractiveButton>Ask AI</InteractiveButton> */}
                </LazyLoad>
              )}
            </div>
            <LazyLoad>
              <CodeEditor
                className={``}
                code={topTemplate}
                maxHeight="10.5rem"
                language={`javascript`}
                readOnly
                showLineNumbers={false}
              />
            </LazyLoad>
            {!code && view === Views.BasicRouteEditor ? null : (
              <div className="relative h-[25rem] min-h-[25rem]">
                <LazyLoad>
                  <CodeEditor
                    className={``}
                    code={code}
                    language={`javascript`}
                    onChange={(value) => setCode(value)}
                    readOnly={view === Views.BasicRouteEditor}
                    showLineNumbers={false}
                  />
                </LazyLoad>
                {view === Views.BasicRouteEditor ? null : (
                  <div className="absolute right-2 top-2 m-auto h-fit w-fit">
                    <LazyLoad>
                      <DropdownVariables
                        variables={variables}
                        onSelect={(value) =>
                          setCode((prev) => `${prev} ${value}`)
                        }
                      />
                    </LazyLoad>
                  </div>
                )}
              </div>
            )}
            <LazyLoad>
              <CodeEditor
                className={``}
                code={bottomTemplate}
                maxHeight="15.5rem"
                language={`javascript`}
                readOnly
                showLineNumbers={false}
              />
            </LazyLoad>
          </div>
        </LazyLoad>
      </ModalSidebar>
    </LazyLoad>
  );
};

export default RouteLogic;
