import React, { useCallback, 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 { MultiSelect } from "@/components/MultiSelect";
import { Collapser } from "@/components/Collapser";
import { WireFrameBuilderContext } from "@/components/WireframeBuilder/reducers/WireframeBuilderContext";
import { ComplexSelect } from "@/components/ComplexSelect";
import { CustomSelect } from "@/components/CustomSelect";
import { VariableConfig } from "../VariableConfig";
import { TrashIcon } from "@/assets/svgs";
import { DropdownVariables } from "@/components/DropdownVariables";
import { MkdControlledInput } from "@/components/MkdControlledInput";
import { ResponseEntries } from "@/components/ResponseEntries";

const statusCodes = {
  400: "Bad Request",
  401: "Unauthorized",
  404: "Not Found",
  500: "Internal Server Error",
};
const ErrorResponseConfig = ({
  parentId,
  workflow,
  title,
  segment,
  variables,
  addVariable,
  onSetData,
}) => {
  const {
    dispatch: globalDispatch,
    state: { selectedRoute },
  } = React.useContext(GlobalContext);

  const { dispatch: wireframeDispatch, state: wireframeState } =
    React.useContext(WireFrameBuilderContext);

  const [responseHeaders, setResponseHeaders] = useState([
    { key: "", value: "" },
  ]);
  const [responseBody, setResponseBody] = useState("");
  const [selectedStatusCode, setSelectedStatusCode] = useState("");

  const addHeaderRow = () => {
    setResponseHeaders([...responseHeaders, { key: "", value: "" }]);
  };

  const deleteRow = useCallback(
    (index) => {
      const tempResponseHeaders = responseHeaders;
      tempResponseHeaders.splice(index, 1);
      setResponseHeaders(() => [...tempResponseHeaders]);
    },
    [responseHeaders]
  );

  const handleHeaderChange = (index, key, value) => {
    const updatedHeaders = [...responseHeaders];
    updatedHeaders[index] = { key, value };
    setResponseHeaders(updatedHeaders);
  };

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

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

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

  useEffect(() => {
    if (workflow?.response_headers && workflow?.response_headers.length) {
      setResponseHeaders(workflow?.response_headers);
    }
    setResponseBody(workflow?.response_body);
    setSelectedStatusCode(workflow?.status_code);
  }, [
    workflow?.response_headers,
    workflow?.response_body,
    workflow?.status_code,
  ]);

  return (
    <>
      <div className="scrollbar-hide ">
        <div className="my-4">
          <label className="mb-2 block text-sm font-bold text-gray-700">
            API Status Code
          </label>
          <CustomSelect
            className="w-full border p-2"
            initialValue={selectedStatusCode}
            onSelectedChange={(value) => setSelectedStatusCode(value)}
            options={Object.keys(statusCodes).map(
              (key) => `${key} - ${statusCodes[key]}`
            )}
            showBorder
          />
        </div>

        {/* <div className="mb-4">
          <label className="mb-2 block text-sm font-bold text-gray-700">
            Response Headers
          </label>
          {responseHeaders &&
            responseHeaders?.length &&
            responseHeaders?.map((header, index) => (
              <div key={index} className="flex h-fit grow items-end gap-2">
                <div className="w-1/2">
                  <LazyLoad>
                    <MkdControlledInput
                      label={"Key"}
                      onChange={(e) =>
                        handleHeaderChange(index, e.target.value, header.value)
                      }
                      value={header?.key}
                      placeholder={`Enter Key`}
                    >
                      <DropdownVariables
                        className={`bg-transparent text-sm`}
                        variables={variables}
                        onSelect={(value) =>
                          handleHeaderChange(
                            index,
                            `${header.key}${value}`,
                            header.value
                          )
                        }
                      />
                    </MkdControlledInput>
                  </LazyLoad>
                </div>
                <span className="self-end">=</span>
                <div className="w-1/2">
                  <LazyLoad>
                    <MkdControlledInput
                      label={"Value"}
                      onChange={(e) =>
                        handleHeaderChange(index, header.key, e.target.value)
                      }
                      value={header?.value}
                      placeholder={`Enter Value`}
                    >
                      <DropdownVariables
                        className={`bg-transparent text-sm`}
                        variables={variables}
                        onSelect={(value) =>
                          handleHeaderChange(
                            index,
                            header.key,
                            `${header.value}${value}`
                          )
                        }
                      />
                    </MkdControlledInput>
                  </LazyLoad>
                </div>
                {responseHeaders?.length > 1 ? (
                  <button onClick={() => deleteRow(index)} className={`w-fit`}>
                    <TrashIcon />
                  </button>
                ) : null}
              </div>
            ))}
          <MkdButton className="mt-5 text-white" onClick={addHeaderRow}>
            Add Header
          </MkdButton>
        </div> */}

        <div>
          <label className="mb-2 block text-sm font-bold text-gray-700">
            Response Body
          </label>
          <LazyLoad>
            <ResponseEntries />
          </LazyLoad>
          {/* <div className={`relative min-h-[25rem] w-full`}>
            <CodeEditor
              className="w-full border p-2"
              code={responseBody}
              onChange={(value) => setResponseBody(value)}
            />

            <div className="absolute right-2 top-2 m-auto h-fit w-fit">
              <DropdownVariables
                variables={variables}
                onSelect={(value) =>
                  setResponseBody((prev) => `${prev} ${value}`)
                }
              />
            </div>
          </div> */}
        </div>
      </div>
    </>
  );
};

export default ErrorResponseConfig;
{
  /* <CustomSelect
className="w-full border p-2"
initialValue={bodyType}
onSelectedChange={(value) => setBodyType(value)}
options={Object.keys(BodyTypes)}
showBorder
/> */
}
