import React, { useCallback, useEffect, useState } from "react";

import { LazyLoad } from "@/components/LazyLoad";
import { GlobalContext, setGLobalProperty } from "@/context/Global";

import { ScaleModalOverlay } from "@/components/ScaleModalOverlay";
import { MkdButton } from "@/components/MkdButton";
import { RouteIfControlConditions } from "../RouteIfControlConditions";
import { ModalSidebar } from "@/components/ModalSidebar";
import { generateUUID } from "@/utils/utils";
import { MkdControlledInput } from "@/components/MkdControlledInput";
import { DropdownVariables } from "@/components/DropdownVariables";
import { TrashIcon } from "@/assets/svgs";
import { DropdownOptions } from "@/components/DropdownOptions";
import { IfOperators } from "../IfOperators";
import { simpleOperatorMap } from "@/utils/constants";

const RouteIfControlModal = ({
  open,
  onToggleModal,
  parentRef,
  workflow,
  addNewCondition,
  updateWorkflow,
  variables,
  // variables,
}) => {
  const {
    dispatch: globalDispatch,
    state: { selectedRoute, configModalOpen },
  } = React.useContext(GlobalContext);
  const [name, setName] = useState("");
  const [data, setData] = useState(null);
  const [selected, setSelected] = useState("===");
  const [ifConditions, setIfConditions] = useState([
    {
      id: generateUUID(),
      left_operand: "",
      operator: "===",
      right_operand: "",
    },
  ]);

  const addRow = () => {
    setIfConditions([
      ...ifConditions,
      {
        id: generateUUID(),
        left_operand: "",
        operator: "===",
        right_operand: "",
      },
    ]);
  };

  const deleteRow = useCallback(
    (index) => {
      const tempIfConditions = ifConditions;
      tempIfConditions.splice(index, 1);
      setIfConditions(() => [...tempIfConditions]);
    },
    [ifConditions]
  );

  const handleInputChange = (index, key, value) => {
    const updateIfConditions = [...ifConditions];
    updateIfConditions[index] = { ...updateIfConditions[index], [key]: value };
    setIfConditions(() => [...updateIfConditions]);
    setData((prev) => ({ ...prev, conditions: updateIfConditions }));
  };
  const onSave = useCallback(() => {
    updateWorkflow(workflow?.id, data);
  }, [data]);

  useEffect(() => {
    if (workflow?.coditions && workflow?.coditions.length) {
      setIfConditions(workflow?.coditions);
    }
    setName(workflow?.action_name);
    // setSelectedStatusCode(workflow?.status_code);
  }, [workflow?.coditions]);

  useEffect(() => {
    setData((prev) => ({ ...prev, action_name: name }));
  }, [name]);

  useEffect(() => {
    setData((prev) => ({ ...prev, conditions: ifConditions }));
  }, [ifConditions?.length]);

  useEffect(() => {
    setData(() => workflow);
  }, []);

  return (
    <ModalSidebar
      isModalActive={open}
      showHeader
      customMinWidthInTw="min-w-[50%] max-w-[50%] w-[50%] overflow-x-hidden"
      title={"If Control"}
      headerContent={
        <div className="flex w-full justify-end gap-3 self-end">
          <button
            onClick={() => {
              onToggleModal(false);
            }}
          >
            Cancel
          </button>
          <MkdButton showPlus={false} onClick={onSave}>
            Save
          </MkdButton>
        </div>
      }
      closeModalFn={() => onToggleModal(false)}
    >
      <div className="flex w-full min-w-full flex-col items-start justify-start px-5 ">
        {/*  */}
        <div className="w-full grow">
          {/* <div className="sticky mb-5 flex"> */}
          {/* <i className="text-small-plus fa-solid fa-split text-controlBase"></i> */}
          {/* <span className="text-lg leading-none"></span> */}
          {/* </div> */}

          <div className="mb-5 w-full">
            <MkdControlledInput
              label={"Action Name"}
              onChange={(e) => setName(e.target.value)}
              value={name}
              placeholder={`Enter a Name for your Action`}
            />
          </div>

          <LazyLoad>
            <div className="mb-4">
              <label className="mb-2 block text-sm font-bold text-gray-700">
                Conditions
              </label>
              {ifConditions &&
                ifConditions?.length &&
                ifConditions?.map((ifCondition, index) => (
                  <div key={index} className="flex h-fit grow items-end gap-2">
                    <div className="w-1/2">
                      <LazyLoad>
                        <MkdControlledInput
                          label={""}
                          onChange={(e) =>
                            handleInputChange(
                              index,
                              "left_operand",
                              e.target.value
                            )
                          }
                          value={ifCondition?.left_operand}
                          // placeholder={`Enter Key`}
                        >
                          <DropdownVariables
                            className={`bg-transparent text-sm`}
                            variables={variables}
                            onSelect={(value) =>
                              handleInputChange(
                                index,
                                "left_operand",
                                `${ifCondition.left_operand}${value}`
                              )
                            }
                          />
                        </MkdControlledInput>
                      </LazyLoad>
                    </div>
                    <div className="max-fit flex w-fit min-w-fit grow items-center gap-2">
                      <span className="self-end">is</span>
                      <LazyLoad>
                        <DropdownOptions
                          icon={simpleOperatorMap[ifCondition?.operator]}
                        >
                          <IfOperators
                            selected={ifCondition?.operator}
                            onSelect={(value) =>
                              handleInputChange(index, "operator", value)
                            }
                          />
                        </DropdownOptions>
                      </LazyLoad>
                    </div>
                    <div className="w-1/2">
                      <LazyLoad>
                        <MkdControlledInput
                          label={""}
                          onChange={(e) =>
                            handleInputChange(
                              index,
                              "right_operand",
                              e.target.value
                            )
                          }
                          value={ifCondition.right_operand}
                          // placeholder={`Enter Value`}
                        >
                          <DropdownVariables
                            className={`bg-transparent text-sm`}
                            variables={variables}
                            onSelect={(value) =>
                              handleInputChange(
                                index,
                                "right_operand",
                                `${ifCondition.right_operand}${value}`
                              )
                            }
                          />
                        </MkdControlledInput>
                      </LazyLoad>
                    </div>
                    {ifConditions?.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>
            {/* <RouteIfControlConditions conditions={workflow?.conditions} /> */}
          </LazyLoad>
          {/*  */}
          <div className="w-full">
            <MkdButton onClick={() => addRow()}>Add condition </MkdButton>
          </div>
        </div>

        {/*  */}
      </div>
    </ModalSidebar>
  );
};

export default RouteIfControlModal;
