import React, { useEffect, useRef, useState } from "react";
import { LazyLoad } from "@/components/LazyLoad";
import { GlobalContext, setGLobalProperty } from "@/context/Global";
import { StringCaser } from "@/utils/utils";
import { ScaleModalOverlay } from "@/components/ScaleModalOverlay";
import { MkdButton } from "@/components/MkdButton";
import { CodeEditor } from "@/components/CodeEditor";
import { DropdownVariables } from "@/components/DropdownVariables";
import WireframeSDK from "@/utils/WireframeSDK";
import { LoadCheckIcon } from "@/assets/svgs"; // Assuming you have this icon
import { WireFrameBuilderContext } from "../../../WireframeBuilder/reducers/WireframeBuilderContext";

const CustomCodeConfig = ({
  parentRef,
  workflow,
  title,
  onSetData,
  parentId,
  segment,
  variables,
}) => {
  const {
    dispatch: globalDispatch,
    state: { selectedRoute },
  } = React.useContext(GlobalContext);
  const { dispatch: builderDispatch, state: builderState } = React.useContext(
    WireFrameBuilderContext
  );
  const [code, setCode] = useState("");
  const [comments, setComments] = useState("");
  const [isLoading, setIsLoading] = useState(false);

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

  const handleGenerateEndpointsLogic = async () => {
    setIsLoading(true);
    try {
      const wSDK = new WireframeSDK();
      const res = await wSDK.customAICompletion(
        selectedRoute?.code || "",
        comments,
        builderState.project.slug
      );

      if (!res.error) {
        setCode(res.model);
        setComments("");
      }
      setGLobalProperty(globalDispatch, res.model, "custom_code");
    } catch (error) {
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="my-5">
      <h5>{title ?? "CODE:"}</h5>
      <div className="flex items-center justify-between">
        <textarea
          placeholder="Write Comment.."
          className="w-full resize-none rounded-lg rounded-r-none border border-r-0 border-gray-700 outline-0 focus:ring-0"
          value={comments}
          onChange={(e) => setComments(e.target.value)}
        />
        <button
          onClick={handleGenerateEndpointsLogic}
          className={`my-2 flex h-[58px] w-[120px] items-center justify-center whitespace-nowrap rounded-lg rounded-l-none border border-l-0 border-gray-700 bg-blue-600 px-5 text-white ${
            isLoading ? "cursor-not-allowed" : ""
          }`}
        >
          {isLoading ? (
            <svg
              className="h-5 w-5 animate-spin text-white"
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
            >
              <circle
                className="opacity-25"
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                strokeWidth="4"
              ></circle>
              <path
                className="opacity-75"
                fill="currentColor"
                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
              ></path>
            </svg>
          ) : (
            "Ask AI"
          )}
        </button>
      </div>

      <div className="relative h-[25rem] min-h-[25rem] border-2">
        <CodeEditor
          className={``}
          code={code}
          language={`javascript`}
          onChange={(value) => setCode(value)}
        />
        <div className="absolute right-2 top-2 m-auto h-fit w-fit">
          <DropdownVariables
            variables={variables}
            onSelect={(value) => setCode((prev) => `${prev} ${value}`)}
          />
        </div>
      </div>
    </div>
  );
};

export default CustomCodeConfig;
