/* eslint-disable @typescript-eslint/no-explicit-any */
import { useCallback, useEffect, useState } from "react";
import { useDispatch, useSelector, useStore } from "react-redux";
// import { useParams } from "react-router-dom";
import { getIsOnline } from "@/redux/config/configSelector";
import { configActions } from "@/redux/config/configSlice";
import { ImpaktMode } from "@/redux/config/configState";
import { actionActions } from "@/redux/currentApp/action/actionSlice";
import { componentsActions } from "@/redux/currentApp/components/componentsSlice";
import { executionActions } from "@/redux/currentApp/executionTree/executionSlice";

import { DisplayNameGenerator } from "@/utils/generators/generateDisplayName";
// import { flatTreeToMap } from "../utils/componentNode/flatTree";
import {
  ComponentsState,
  // ComponentTreeNode,
} from "@/redux/currentApp/components/componentsState";
import { ActionContent, ActionItem } from "@/redux/currentApp/action/interface";
import { DependenciesState } from "@/redux/currentApp/executionTree/executionState";
// import { fixedComponentsToNewComponents } from "./fixedComponents";
import { fixedActionToNewAction } from "./fixedAction";
import { fixedComponentsToNewComponents } from "./fixedComponents";
import { flatTreeToMap } from "@/redux/utils";
// import _ from "lodash";
// import { styleActions } from "@/redux/currentApp/style/cursorSlice";
import { StyleState } from "@/redux/currentApp/style/styleState";
import { ControllerActions } from "@/redux/currentApp/executionController/controllerSlice";
import _ from "lodash";
import { useDestroyApp } from "./useDestroyExecutationTree";
import { ImpaktProps } from "@/lib";
import { styleActions } from "@/redux/currentApp/style/cursorSlice";
import { resourceActions } from "@/redux/resource/resourceSlice";
// import axios from "axios";
export interface CurrentAppResp {
  cloneData: any;
  appInfo: any;
  components: ComponentsState;
  // getResource: () => Promise<RestApiResource<RestApiAuth>>;

  action: ActionItem<ActionContent>[];
  style: StyleState;
  dependenciesState: DependenciesState;
  executionState: Record<string, any>;
  impaktData: any;
}
export const updateCurrentAppInfo = (
  cloneData: any,
  data: CurrentAppResp,
  mode: ImpaktMode,
  appId: string,
  teamID: string,
  uid: string,
  impaktData: any,
  store: any
) => {
  // if (data.components.templatName) {
  if (data.style) {
    store.dispatch(styleActions.initStyleListReducer(data.style));
  }
  store.dispatch(
    configActions.resetLayoutSection({
      body: "active",
      other: "active",
    })
  );
  // }
  if (mode !== "preview" && mode !== "production") {
    store.dispatch(
      ControllerActions.updateControllerListReducer(impaktData)
    );
  }
  store.dispatch(configActions.updateImpaktAppsMode(mode));
  // store.dispatch(appInfoActions.updateAppInfoReducer(data.appInfo))
  const fixedComponents = fixedComponentsToNewComponents(cloneData);
  store.dispatch(
    componentsActions.initComponentReducer(flatTreeToMap(fixedComponents))
  );
  const fixedActions: any = fixedActionToNewAction(data.action);
  if (fixedActions.length > 0) {
    store.dispatch(actionActions.initActionListReducer(fixedActions));
  }
  // data.getResource().then((response) => {
  //   if (mode !== "preview") {
  //     store.dispatch(
  //       resourceActions.updateResourceListReducer( [
  //         {
  //           resourceName: "ImapktApps",
  //           resourceType: "restapi",
  //           resourceID: "restapi-o1",
  //           content: response,
  //         },
  //       ])
  //     );
  //   }
  // });

  DisplayNameGenerator.initApp(appId, teamID, uid, data.components.namePrefix);
  DisplayNameGenerator.updateDisplayNameList(cloneData, fixedActions);
  store.dispatch(executionActions.startExecutionReducer());
  if (mode === "edit" && fixedActions.length > 0) {
    store.dispatch(configActions.changeSelectedAction(fixedActions[0]));
  }
};

export const useInitBuilderApp = (
  mode: ImpaktMode,
  impaktData: ImpaktProps
) => {
  // const { appId = "" } = useParams();
  const  appId = "" 
  let model: any = {};
  if (mode !== "preview") {
    model = impaktData.model;
  } else {
    model = impaktData;
  }
  const dispatch = useDispatch();
  const isOnline = useSelector(getIsOnline);
  const [loadingState, setLoadingState] = useState(true);
  const [errorState, setErrorState] = useState(false);
  const { uid, teamID } = {
    uid: "",
    teamID: "",
  };
  useDestroyApp();

  const handleCurrentApp = useCallback(
    (cloneData, data: CurrentAppResp, impaktData: any, store: any) => {
      updateCurrentAppInfo(
        cloneData,
        data,
        mode,
        appId,
        teamID,
        uid,
        impaktData,
        store
      );
    },
    [mode, appId, teamID, uid]
  );

  const store = useStore();
  useEffect(() => {
    const controller = new AbortController();
    if (isOnline && model) {
      setErrorState(false);
      setLoadingState(true);
      if (model?.components?.root) {
        const actualComponents = _.cloneDeep(model.components);
        const cloneModel = buildTree(actualComponents);
        cloneModel.components = actualComponents;
        handleCurrentApp(cloneModel, model, impaktData, store);
        impaktData.getResource().then((response) => {
          if (mode !== "preview") {
            dispatch(
              resourceActions.updateResourceListReducer([
                {
                  resourceName: "ImapktApps",
                  resourceType: "impaktapps",
                  resourceID: "restapi-o1",
                  content: response,
                },
              ])
            );
          }
        });
        impaktData.getPages().then((response) => {
          if (mode !== "preview") {
            dispatch(ControllerActions.setResourcePagesReducer(response));
          }
        });
        impaktData.getRules().then((response) => {
          if (mode !== "preview") {
            dispatch(ControllerActions.setResourceRulesReducer(response));
          }
        });
        impaktData.getStyles().then((response) => {
          if (mode !== "preview") {
            dispatch(styleActions.initStyleListReducer(response));
          }
        });
      }
      setLoadingState(false);
    }

    return () => {
      controller.abort();
    };
  }, [dispatch, handleCurrentApp, impaktData, isOnline, model]);

  return { loadingState, errorState };
};
export function buildTree(input) {
  if (!input.root) {
    return input;
  }
  function buildNode(nodeKey, parentNodeKey) {
    const node = input[nodeKey];
    const children = node.childrenNode
      ? node.childrenNode.map((childKey) => buildNode(childKey, nodeKey))
      : null;

    return {
      ...node,
      parentNode: parentNodeKey,
      childrenNode: children,
    };
  }

  const rootNodeKey = "root";
  return buildNode(rootNodeKey, "");
}

// const [count, setCount] = useState(0);
// useEffect(() => {
//   const controller = new AbortController();
//   if (isOnline && count < 1) {
//     setCount(2);
//     setErrorState(false);
//     setLoadingState(true);
//     const res = _.cloneDeep( impaktData||JSON.parse(localStorage.getItem("pageConfig")));
//     if (res) {
//       console.log("res >>", res.components);
//       const actualComponents = buildTree(res.components);
//       res.components =
//       //  impaktData?impaktData.components:
//        actualComponents;
//       console.log("res >>", res.components)
//       handleCurrentApp(res,impaktData);
//     }
//     setLoadingState(false);
//   }

//   return () => {
//     controller.abort();
//   };
// }, [appId, count, dispatch, handleCurrentApp, impaktData, isOnline, teamID, version]);
