import * as React from "react";
import { DrawersSceneManager, SceneMangerStore, StoreMode } from "./scene_manager_store";
import { observer } from "mobx-react-lite";
import { Drawer, Popover } from "antd";
import { useNavigate, useParams } from "react-router-dom";
import { MainPage } from "../../../core/ui/pages/main_page";
import { CoreText, CoreTextType } from "../../../core/ui/text/text";
import { CoreButton } from "../../../core/ui/button/button";
import { CoreInput } from "../../../core/ui/input/input";
import { DrawersDataset } from "../../dataset/dataset_store";
import { Icon } from "../../../core/ui/icons/icons";
import { sceneManagerForms } from "./forms/scene_manager_forms";
import { SceneMode } from "../model/scene_view";

export const SceneManagerPath = "/scene/manager/";

export const SceneManger = observer(() => {
  const canvasRef = React.useRef<HTMLCanvasElement>(null);
  const [store] = React.useState(() => new SceneMangerStore());
  const id = useParams().id as string;
  const navigate = useNavigate();
  store.initParam(id);

  React.useEffect(() => {
    store.init();
    store.loadScene(canvasRef.current!);
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = "scroll";
      store.dispose();
    };
  }, [id, store]);

  return (
    <MainPage
      page={"Сцена"}
      panelStyle={{
        display: store.storeMode.isEqualR(StoreMode.sceneInstance).fold(
          () => "",
          () => "none"
        ),
      }}
      panelChildren={
        <div style={{ width: "100%", height: "100%" }}>
          <div style={{ height: 260, width: "100%", padding: 10 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <CoreText text="Сцена" type={CoreTextType.large} />
              <Popover
                placement="bottom"
                color="rgba(104, 80, 164, 1)"
                content={
                  <div>
                    {store.popoverItems.map((el, i) => (
                      <div key={i} onClick={() => el.fn()}>
                        <CoreText text={el.name} type={CoreTextType.medium} color="white" />
                      </div>
                    ))}
                  </div>
                }
              >
                <span>
                  <CoreButton text="Добавить" filled={true} />
                </span>
              </Popover>
              <div style={{ position: "relative" }}>
                <div style={{ position: "absolute" }}>
                  <div style={{ position: "relative", left: 20 }}>
                    {store.sceneHelperInstruments.map((el, i) => (
                      <div
                        key={i}
                        onClick={() => el.onClick()}
                        style={{
                          marginTop: 4,
                          width: 50,
                          height: 50,
                          backgroundColor: el.isSelected ? "rgba(160, 132, 255, 1)" : "rgba(99, 81, 159, 1)",
                          border: "1px solid",
                          borderRadius: 5,
                        }}
                      >
                        <Icon type={el.icon} />
                      </div>
                    ))}
                    {store.isVisibleSaveButton ? (
                      <>
                        <div
                          onClick={() => store.sceneSave()}
                          style={{
                            marginTop: 4,
                            width: 50,
                            height: 50,
                            backgroundColor: "rgba(99, 81, 159, 1)",
                            border: "1px solid",
                            borderRadius: 5,
                          }}
                        >
                          <Icon type={SceneMode.Save} />
                        </div>
                      </>
                    ) : null}
                  </div>
                </div>
              </div>
            </div>
            <div style={{ height: 10 }} />
            <div
              style={{
                borderRadius: 7,
                height: 200,
                width: "-webkit-fill-available",
                backgroundColor: "white",
                overflowX: "auto",
              }}
            >
              {store.sceneItems.map((el, index) => (
                <div
                  key={index}
                  style={{
                    display: "flex",
                    backgroundColor: el.isSelected
                      ? "rgba(104, 80, 164, 0.47)"
                      : index.isEven()
                      ? "rgba(217, 217, 217, 0.27)"
                      : "",
                    alignItems: "center",
                    flexDirection: "row",
                    justifyContent: "space-between",
                    width: "100%",
                  }}
                  onClick={() => store.selectSceneItems(el.name, index, !el.isSelected, el.icon)}
                >
                  <Icon width={13} height={13} type={el.icon} style={{ marginLeft: 10 }} />
                  <div style={{ width: 10 }} />
                  <CoreText text={el.name} type={CoreTextType.small} />
                  <Icon
                    type="DeleteCircle"
                    width={13}
                    isNeedStopPropagation={true}
                    height={13}
                    onClick={() => store.deleteSceneItem(el)}
                    style={{ marginRight: 10 }}
                  />
                </div>
              ))}
            </div>
          </div>
          <div style={{ height: 20 }} />
          <div
            style={{
              width: "-webkit-fill-available",
              height: "60%",
              borderRadius: 7,
              backgroundColor: "white",
              margin: 10,
            }}
          >
            {sceneManagerForms(store.activeFormDependency ?? {}, store).map((el, i) =>
              el.name.isEqualR(store.activeFormType ?? "").fold(
                () => <span key={i}>{el.component}</span>,
                () => <span key={i}></span>
              )
            )}
          </div>
        </div>
      }
      bodyChildren={
        <>
          {store.storeMode.isEqual(StoreMode.sceneInstance) ? (
            <>
              <canvas ref={canvasRef} style={{ overflow: "hidden" }} />
            </>
          ) : (
            <div
              style={{
                width: "100%",
                height: "100vh",
                background: "rgba(246, 242, 249, 1)",
                padding: 50,
                paddingLeft: 70,
                paddingRight: 70,
              }}
            >
              <div style={{ width: "100%", height: "100%", background: "white" }}>
                <div style={{ width: "100%", textAlign: "center" }}>
                  <CoreText text="Сцены" type={CoreTextType.big} />
                  <CoreText
                    text="Создать новую сцену?"
                    onClick={() => store.editDrawer(DrawersSceneManager.NewScene, true)}
                    type={CoreTextType.small}
                    color="rgba(68, 142, 247, 1)"
                    style={{ cursor: "pointer" }}
                  />

                  <div>
                    {store.scenes.map((el, i) => (
                      <div
                        key={i}
                        style={{
                          border: "1px solid #CAC4D0",
                          margin: 10,
                          height: 60,
                          alignItems: "center",
                          borderRadius: 7,
                          display: "flex",
                          justifyContent: "space-between",
                          backgroundColor: "rgba(104, 80, 164, 1)",
                          color: "white",
                          paddingLeft: 10,
                        }}
                      >
                        <CoreText text={el.name} type={CoreTextType.large} color="white" />
                        <CoreButton
                          text="Перейти"
                          onClick={() => {
                            navigate(`${SceneManagerPath}${el._id}`);
                          }}
                          textStyle={{ color: "black", textAlign: "center" }}
                          style={{ marginRight: 10, backgroundColor: "white", width: 126 }}
                        />
                      </div>
                    ))}
                  </div>
                </div>
                <div></div>
              </div>
              <canvas ref={canvasRef} style={{ overflow: "hidden" }} />
              <div
                style={{
                  display: "flex",
                  flexDirection: "row",
                  alignContent: "center",
                  justifyContent: "space-between",
                  position: "absolute",
                  width: "100vw",
                }}
              />
              <Drawer
                title={store.titleDrawer}
                destroyOnClose={true}
                onClose={() => store.editDrawer(DrawersSceneManager.NewScene, false)}
                open={store.drawers.find((el) => el.name === DrawersSceneManager.NewScene)?.status}
              >
                <div
                  style={{ display: "flex", flexDirection: "column", justifyContent: "space-between", height: "100%" }}
                >
                  <CoreInput
                    value={store.viewModel.name}
                    label={"Имя сцены"}
                    onChange={(text) => store.updateForm({ name: text })}
                  />

                  <div style={{ display: "flex" }}>
                    <CoreButton text="Сохранить" filled={true} onClick={() => store.createNewScene()} />
                    <div style={{ width: 10 }} />
                    <CoreButton text="Отмена" onClick={() => store.editDrawer(DrawersDataset.NewDataset, false)} />
                  </div>
                </div>
              </Drawer>
            </div>
          )}
        </>
      }
    />
  );
});
