import * as React from "react";
import { useRete } from "rete-react-plugin";
import { createEditor } from "./ui/editor/editor";
import { SkillTree } from "./ui/skill_tree/skill_tree";
import { BehaviorTreeBuilderStore, DrawerState } from "./behavior_tree_builder_store";
import { observer } from "mobx-react-lite";
import { match } from "ts-pattern";
import { Icon } from "../../../core/ui/icons/icons";
import { CoreText, CoreTextType } from "../../../core/ui/text/text";
import { useNavigate, useParams } from "react-router-dom";
import { IForms, forms } from "./ui/forms/forms";
import { ButtonV2, ButtonV2Type } from "../../../core/ui/button/button_v2";
import { CoreCard } from "../../../core/ui/card/card";
import { themeStore } from "../../..";
import { CoreModal } from "../../../core/ui/modal/modal";
import { InputV2 } from "../../../core/ui/input/input_v2";
import { SelectV2 } from "../../../core/ui/select/select_v2";
import { MainPageV2 } from "../../../core/ui/pages/main_page_v2";
import { DrawerV2 } from "../../../core/ui/drawer/drawer";
import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";

export const behaviorTreeBuilderScreenPath = "behavior/tree/screen/path";

export interface DOMReact {
  x: number;
  y: number;
  width: number;
  height: number;
  top: number;
  right: number;
  bottom: number;
  left: number;
}

export const behaviorTreeBuilderStore = new BehaviorTreeBuilderStore();

export const BehaviorTreeBuilderPath = (id?: string) => {
  if (id) {
    return `/behavior/tree/${id}`;
  }
  return `/behavior/tree/`;
};

export const isBtScreen = () =>
  Boolean(window.location.href.match(new RegExp(BehaviorTreeBuilderPath()))?.at(0)) ?? false;

export const BehaviorTreeBuilderScreen = observer(() => {
  const navigate = useNavigate();
  const { id } = useParams();
  // @ts-expect-error
  const [ref] = useRete<HTMLDivElement>(createEditor);
  const store = behaviorTreeBuilderStore;
  React.useEffect(() => {
    if (ref.current) {
      // @ts-expect-error
      const domReact: DOMReact = ref.current.getBoundingClientRect();
      store.dragZoneSetOffset(0, domReact.y, domReact.width, domReact.height);
    }
  }, [ref.current]);

  React.useEffect(() => {
    store.init(navigate).then(() => store.initParam(id));
    return () => {
      store.dispose();
    };
  }, []);
  return (
    <MainPageV2
      rightChild={
        <>
          <div
            style={{
              width: "100%",
              display: "flex",
              flexDirection: "row",
              justifyContent: "end",
              paddingRight: 30,
              alignItems: "center",
            }}
          >
            {/* <ButtonV2 style={{ height: 40 }} onClick={() => {}} text="Запуск" textColor={themeStore.theme.black} />
            <div style={{ width: 10 }} />
            <ButtonV2
              style={{ height: 40 }}
              onClick={() => {}}
              text="Стоп"
              type={ButtonV2Type.empty}
              textColor={themeStore.theme.greenWhite}
            />
            <div style={{ width: 10 }} /> */}
            {store.isNeedSaveBtn ? (
              <div
                style={{
                  backgroundColor: store.isNeedSaveBtn ? themeStore.theme.greenWhite : undefined,
                  height: 40,
                  textAlign: "center",
                  alignContent: "center",
                  width: 40,
                  borderRadius: 100,
                }}
              >
                {store.isNeedSaveBtn ? (
                  <Icon style={{ height: 21 }} onClick={() => store.onClickSaveBehaviorTree()} type="Floppy" />
                ) : undefined}
              </div>
            ) : (
              <></>
            )}
          </div>
        </>
      }
      style={{ position: "absolute", height: "100%", overflow: "hidden" }}
      bgColor={themeStore.theme.black}
      children={
        <>
          <>
            <div
              style={{
                height: "100%",
                width: 300,
                zIndex: 10,
                position: "absolute",
                display: "flex",
                flexDirection: "column",
                justifyContent: "space-between",
                backgroundColor: themeStore.theme.surfaceContainerLow,
              }}
            >
              <div style={{ margin: 20 }}>
                <div style={{ height: 58, alignContent: "center" }}>
                  <CoreText
                    text="Поведение"
                    type={CoreTextType.mediumV2}
                    color={themeStore.theme.onSurfaceVariant}
                    style={{ marginLeft: 20 }}
                  />
                  <div style={{ width: "100%", height: 1, backgroundColor: themeStore.theme.outlineVariant }} />
                </div>
                {store.skillTemplates ? <SkillTree skills={store.skillTree} dragEnd={store.dragEnd} /> : null}
              </div>
            </div>

            <div
              style={{
                position: "absolute",
                left: 300,
                height: "100%",
                width: "calc(100% - 300px)",
              }}
            >
              <PanelGroup direction="horizontal" style={{ width: "100%" }}>
                <Panel>
                  <div
                    ref={ref}
                    className="dotted"
                    style={{
                      width: "100%",
                      height: "100%",
                      backgroundSize: "20px 20px",
                    }}
                  />
                </Panel>
                <PanelResizeHandle>
                  <div style={{ width: 10, height: "100%", backgroundColor: "beige" }}></div>
                </PanelResizeHandle>
                <Panel defaultSize={0}> </Panel>
              </PanelGroup>
            </div>
          </>

          <DrawerV2
            title={store.titleDrawer}
            onClose={() => store.editDrawer(DrawerState.editThreadBehaviorTree, false)}
            isOpen={store.drawers.find((el) => el.name === DrawerState.editThreadBehaviorTree)?.status}
          >
            <div style={{ display: "flex", flexDirection: "column", justifyContent: "space-between", height: "100%" }}>
              <div style={{ height: "100%" }}>
                {store.skillTemplates?.getForms(store.selected ?? "").map((formType, index) =>
                  forms(
                    store.filledOutTemplates?.getDependencyBySkillLabelAndType(
                      forms(null, () => {}, store).find((form) => form.name.isEqual(formType))?.name ?? "",
                      store.selectedSid ?? ""
                    ),
                    (dependency) => store.formUpdateDependency(dependency, formType),
                    store
                  )
                    .rFind<IForms>((form) => form.name.isEqual(formType))
                    .fold(
                      (s) => (
                        <div key={index} style={{ height: "100%" }}>
                          {s.component}
                        </div>
                      ),
                      () => (
                        <div key={index + "error"} style={{ height: "100%" }}>
                          Error: Unknown form type {formType}
                        </div>
                      )
                    )
                )}
              </div>
            </div>
          </DrawerV2>
        </>
      }
    />
  );
});
