import { CSSProperties, FC, useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useDispatch, useSelector } from "react-redux";
import { CodeEditor } from "@/components/CodeEditor";
import { getSelectedClass } from "@/redux/config/configSelector";
import { globalDataPanelContainerStyle, inputAreaStyle } from "./style";
import { VALIDATION_TYPES } from "@/utils/validationFactory";
import { Button } from "@mui/material";
import {
  actionContentStyle,
  actionPanelStyle,
  stylePanelContainerStyle,
} from "../../Actions/ActionPanel/style";
import { globalColor } from "@/utils/colorBuilder";
import { getStringSnippets, isDynamicStringSnippet } from "@/redux/utils";
import { createNotification } from "@/utils/Notification";
import { styleActions } from "@/redux/currentApp/style/cursorSlice";
import {
  getCachedClass,
  getClaasesObject,
} from "@/redux/currentApp/style/styleSelector";
// import { ControllerActions } from "@/lib";
import { getControllerSetStyleFunctions } from "@/redux/currentApp/executionController/controllerSelector";
import { Default_Theme } from "@/redux/currentApp/style/styleState";
const StylePanel: FC = () => {
  const currentClass = useSelector(getCachedClass);
  const selectedClass = useSelector(getSelectedClass);
  const classMap = useSelector(getClaasesObject);
  const [value, setValue] = useState("");
  const setStyles = useSelector(getControllerSetStyleFunctions);
  const { t } = useTranslation();
  const dispatch = useDispatch();
  useEffect(() => {
    const isObject = typeof classMap[selectedClass] === "object";
    setValue(
      isObject
        ? `{{ ${JSON.stringify(classMap[selectedClass])} }}`
        : (classMap[selectedClass] as string)
    );
  }, [classMap, selectedClass]);
  const handleOnChangeValue = (value: string) => {
    setValue(value);
    dispatch(
      styleActions.updateCachedClass({
        ...currentClass,
        initialValue: value,
      })
    );
  };
  const saveHandler = useCallback(() => {
    const dynamicStrings = getStringSnippets(value as string);
    dynamicStrings.forEach((dynamicString) => {
      if (isDynamicStringSnippet(dynamicString)) {
        try {
          dispatch(styleActions.updateCachedClass(value));
          dispatch(
            styleActions.updateStyleClassReducer({
              class: value as CSSProperties,
              className: selectedClass,
            })
          );
          setStyles({
            classes: classMap,
            themes: { Default_Theme: Default_Theme },
            appliedTheme: "Default_Theme",
          });
          const notification = createNotification();
          notification.show({
            title: `Save Successfully`,
            content: "Class added/updated Successfully",
            duration: 500,
            type: "success",
          });
        } catch (e) {
          const notification = createNotification();
          notification.show({
            title: `Error on Save`,
            content: e.message,
            duration: 500,
            type: "error",
          });
        }
      }
    });

    // });
  }, [dispatch, selectedClass, value]);
  return (
    <>
      <div css={actionPanelStyle}>
        <div css={stylePanelContainerStyle}>
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              padding: "10px auto",
              borderBottom: `0.5px solid ${globalColor("gray-04")}`,
            }}
          >
            <div
              style={{
                fontSize: "12px",
                color: "gray",
                width: "70%",
                padding: "10px",
              }}
            >
              Style Configuration
            </div>
            <div style={{ display: "flex", justifyContent: "flex-end" }}>
              <Button
                variant="outlined"
                color="success"
                size="small"
                sx={{ fontSize: "10px", padding: "2px", margin: "5px" }}
                onClick={saveHandler}
              >
                Save
              </Button>
            </div>
          </div>
          <div css={globalDataPanelContainerStyle}>
            <div css={actionContentStyle}>
              <div css={inputAreaStyle}>
                <CodeEditor
                  value={value}
                  height="100px"
                  onChange={handleOnChangeValue}
                  expectValueType={VALIDATION_TYPES.OBJECT}
                  modalTitle={t(
                    "editor.data_work_space.global_data_modal.initial_value.label"
                  )}
                  modalDescription={t(
                    "editor.data_work_space.global_data_modal.initial_value.tooltips"
                  )}
                  placeholder={t("Please upadte your style here")}
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

StylePanel.displayName = "StylePanel";

export default StylePanel;
