import React, { useCallback, useEffect, useState } from "react";
import { LazyLoad } from "@/components/LazyLoad";
import { MkdButton } from "@/components/MkdButton";
import { CustomSelect } from "@/components/CustomSelect";
import { HttpMethods } from "@/utils/constants";
import { MkdControlledInput } from "@/components/MkdControlledInput";
import { DropdownVariables } from "@/components/DropdownVariables";
import { TrashIcon } from "@/assets/svgs";
import { ResponseEntries } from "@/components/ResponseEntries";

const AuthTypes = {
  "No Auth": "No Auth",
  "Bearer Token": "Bearer Token",
};
const BodyTypes = {
  JSON: "JSON",
  FormData: "FormData",
};
const HttpRequestConfig = ({ workflow, variables, onSetData }) => {
  const [selectedMethod, setSelectedMethod] = useState("");
  const [httpUrl, setHttpUrl] = useState("");
  const [authType, setAuthType] = useState("No Auth");
  const [authValue, setAuthValue] = useState("");
  const [headers, setHeaders] = useState([{ key: "", value: "" }]);
  const [bodyType, setBodyType] = useState("JSON");
  const [bodyContent, setBodyContent] = useState("");

  const addHeaderRow = () => {
    setHeaders([...headers, { key: "", value: "" }]);
  };
  const deleteRow = useCallback(
    (index) => {
      const tempHeaders = headers;
      tempHeaders.splice(index, 1);
      setHeaders(() => [...tempHeaders]);
    },
    [headers]
  );

  const handleHeaderChange = (index, key, value) => {
    const updatedHeaders = [...headers];
    updatedHeaders[index] = { key, value };
    setHeaders(updatedHeaders);
  };
  const handleInputChange = (state, value) => {
    switch (state) {
      case "authValue":
        if (value) {
          setAuthValue(value);
        } else {
          setAuthValue("");
        }
        break;
    }
  };

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

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

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

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

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

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

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

  useEffect(() => {
    if (workflow?.headers && workflow?.headers?.length) {
      setHeaders(workflow?.headers);
    }
    setSelectedMethod(workflow?.method);
    setHttpUrl(workflow?.request_url);
    setAuthType(workflow?.auth_type);
    setAuthValue(workflow?.auth_value);
    setBodyType(workflow?.body_type);
    setBodyContent(workflow?.body_content);
  }, [
    workflow?.method,
    workflow?.request_url,
    workflow?.auth_type,
    workflow?.auth_value,
    workflow?.headers,
    workflow?.body_type,
    workflow?.body_content,
  ]);

  return (
    <div className="scrollbar-hide max-h-fit">
      <div className={`my-5 flex w-full items-end justify-between gap-2`}>
        <div className="w-[25%]">
          <label className="mb-2 block text-sm font-bold text-gray-700">
            HTTP Method
          </label>
          <CustomSelect
            className="w-full border p-2"
            initialValue={selectedMethod}
            onSelectedChange={(value) => setSelectedMethod(value)}
            options={Object.keys(HttpMethods)}
            showBorder
          />
        </div>
        <div className="grow">
          <LazyLoad>
            <MkdControlledInput
              label={"Http Url"}
              onChange={(e) => setHttpUrl(e.target.value)}
              value={httpUrl}
              placeholder={`Http Url`}
            >
              <DropdownVariables
                className={`bg-transparent text-sm`}
                variables={variables}
                onSelect={(value) => setHttpUrl((prev) => `${prev}${value}`)}
              />
            </MkdControlledInput>
          </LazyLoad>
        </div>
      </div>

      <div className="mb-4">
        <label className="mb-2 block text-sm font-bold text-gray-700">
          Auth Type
        </label>

        <CustomSelect
          className="w-full border p-2"
          initialValue={authType}
          onSelectedChange={(value) => setAuthType(value)}
          options={Object.keys(AuthTypes)}
          showBorder
        />

        {authType !== "No Auth" && (
          <div className="w-full">
            <LazyLoad>
              <MkdControlledInput
                label={"Auth Value"}
                onChange={(e) => handleInputChange("authValue", e.target.value)}
                value={authValue}
                placeholder={`Enter Auth Value`}
              >
                <DropdownVariables
                  className={`bg-transparent text-sm`}
                  variables={variables}
                  onSelect={(value) =>
                    setAuthValue((prev) => `${prev}${value}`)
                  }
                />
              </MkdControlledInput>
            </LazyLoad>
          </div>
        )}
      </div>
      <div className="mb-4">
        <label className="mb-2 block text-sm font-bold text-gray-700">
          Headers
        </label>
        {headers.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>
            {headers?.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 className="mb-4">
        <label className="mb-2 block text-sm font-bold text-gray-700">
          Body Type
        </label>
        <CustomSelect
          className="w-full border p-2"
          initialValue={bodyType}
          onSelectedChange={(value) => setBodyType(value)}
          options={Object.keys(BodyTypes)}
          showBorder
        />
      </div>

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

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

export default HttpRequestConfig;
