/* eslint-disable @typescript-eslint/no-explicit-any */
import { CodeEditor } from "@/components/CodeEditor";
import { getStringSnippets, isDynamicStringSnippet } from "@/redux/utils";
import { evaluateDynamicString } from "@/utils/evaluateDynamicString";
import { VALIDATION_TYPES } from "@/utils/validationFactory";
import { Box, IconButton, MenuItem, Select } from "@mui/material";
import { t } from "i18next";
import { useCallback, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { createNotification } from "@/utils/Notification";
import SaveIcon from "@mui/icons-material/Save";
import { newGenerateComponentNode } from "@/utils/generators/generateComponentNode";
import { DisplayNameGenerator } from "@/utils/generators/generateDisplayName";
import { componentsActions } from "@/redux/currentApp/components/componentsSlice";
import { getExecutionResult } from "@/redux/currentApp/executionTree/executionSelector";
const CONTAINER_OPTIONS = ["Container", "Grid Container", "Form"];
const WidgetMapWithDisplayName = {
  button: "BUTTON_WIDGET",
  checkbox: "CHECKBOX_WIDGET",
  container: "CONTAINER_WIDGET",
  gridcontainer: "GridCONTAINER_WIDGET",
  date: "DATE_WIDGET",
  emptybox: "EMPTY_BOX",
  fileinput: "FILE_INPUT_WIDGET",
  icon: "ICON_WIDGET",
  input: "INPUT_WIDGET",
  label: "LABEL_WIDGET",
  multiselect: "MULTISELECT_WIDGET",
  radio: "RADIO_WIDGET",
  select: "SELECT_WIDGET",
  tabs: "TABS_WIDGET",
  textarea: "TEXT_AREA_WIDGET",
};
const Screen = () => {
  const [value, setValue] = useState(`{{ 
       [
    
       ]
}}`);
  const dispatch = useDispatch();
  const result = useSelector(getExecutionResult);
  const [parent, setParent] = useState("Grid Container");
  const handleOnChangeValue = (value: string) => {
    setValue(value);
  };
  const saveHandler = useCallback(() => {
    const dynamicStrings = getStringSnippets(value);
    const notification = createNotification();
    dynamicStrings.forEach((dynamicString) => {
      if (isDynamicStringSnippet(dynamicString)) {
        try {
          // const globalObj = {};
          // actions.map((e)=>{

          // })
          const calcRes = evaluateDynamicString("", dynamicString, result);
          const componentMaps = calcRes.map((e) => {
            const realDisplayName = DisplayNameGenerator.generateDisplayName(
              WidgetMapWithDisplayName[e.type],
              e.type
            );
            const newComponentNode = newGenerateComponentNode(
              WidgetMapWithDisplayName[e.type],
              realDisplayName,
              e.parentname||"body",
              []
            );
            return newComponentNode;
          });
          dispatch(componentsActions.addComponentReducer(componentMaps));

          notification.show({
            title: `Save Successfully`,
            content: ``,
            duration: 1000,
            type: "success",
          });
        } catch (e) {
          notification.show({
            title: `Failed to build`,
            content: `Invalid Type Given`,
            duration: 1000,
            type: "error",
          });
        }
      }
    });
  }, [dispatch, value]);
  return (
    <Box sx={{ width: "100%" }}>
      <div>
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "flex-end",
          }}
        >
          <div style={{ width: "60%", fontWeight: 600, padding: "5px" }}>
            Screen Builder
          </div>
          <div
            style={{
              width: "35%",
              display: "flex",
              alignContent: "center",
              justifyContent: "flex-end",
              padding: "5px",
            }}
          >
            <Select
              size="small"
              value={parent}
              name="Parent"
              variant="standard"
              label="Parent Type"
              onChange={(e) => setParent(e.target.value)}
            >
              {CONTAINER_OPTIONS.map((e) => {
                return (
                  <MenuItem key={e} value={e} onClick={() => {}}>
                    {e}
                  </MenuItem>
                );
              })}
            </Select>
          </div>
          <div
            style={{
              width: "5%",
              display: "flex",
              alignContent: "center",
              justifyContent: "flex-end",
            }}
          >
            <IconButton
              color="success"
              title="Generate Page"
              onClick={() => {
                saveHandler();
              }}
            >
              <SaveIcon />
            </IconButton>
          </div>
        </div>
      </div>
      <CodeEditor
        value={value}
        height="200px"
        onChange={handleOnChangeValue}
        expectValueType={VALIDATION_TYPES.ARRAY}
        showLineNumbers
        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 style={{ height: "100px" }}></div>
    </Box>
  );
};

export default Screen;
