import React from "react";
import { Drawer, Modal } from "antd";
import { observer } from "mobx-react-lite";
import { MainPage } from "../../../core/ui/pages/main_page";
import { CoreText, CoreTextType } from "../../../core/ui/text/text";
import { DrawersSkill, CalculationInstanceStore, StoreTypes } from "./calculation_instance_store";
import { CoreInput } from "../../../core/ui/input/input";
import { CoreButton } from "../../../core/ui/button/button";
import { CoreSelect } from "../../../core/ui/select/select";
import { ModelMachineLearningTypes } from "../model/calculation_model";
import { CardModel, getModelCard } from "./ui/cards/get_model_card";
import { FormBuilder } from "../../../core/ui/form_builder/form_builder";
import { match } from "ts-pattern";
import { TemplateModelCard } from "./ui/template_model_card";
import { Icon } from "../../../core/ui/icons/icons";
import { useStore } from "../../../core/helper/use_store";
import { FormBuilderValidationModel } from "../../../core/model/form_builder_validation_model";
import { InputV2 } from "../../../core/ui/input/input_v2";

interface IItem {
  name: string;
  isActive: boolean;
}

const skills: IItem[] = [{ name: "ML", isActive: true }];

export const CalculationInstanceScreenPath = "/calculation";

export const CalculationInstanceScreen = observer(() => {
  const store = useStore(CalculationInstanceStore);

  return (
    <>
      <MainPage
        page={"модели"}
        panelChildren={
          <div style={{ justifyContent: "center", display: "flex", padding: 10 }}>
            {skills.map((el, i) => (
              <CoreText key={i} text={el.name} type={CoreTextType.header} />
            ))}
          </div>
        }
        bodyChildren={
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(auto-fill, minmax(220px,1px))",
              width: "100%",
              gap: 20,
              margin: 12,
              overflow: "auto",
              height: window.innerHeight,
            }}
          >
            {store.calculationInstances?.map((el, i) => {
              return (
                <span key={i}>
                  {getModelCard(
                    el,
                    () => store.makeEditProcess(el),
                    () => store.deleteInstance(el._id ?? ""),
                    () => store.execSkill(el._id ?? ""),
                    () => store.execSkill(el._id ?? "")
                  )}
                </span>
              );
            })}

            <div
              onClick={() => {
                store.editDrawer(DrawersSkill.NEW_SKILL, true);
              }}
              style={{
                background: "rgb(247, 242, 250)",
                width: 150,
                height: 80,
                alignContent: "center",
                textAlignLast: "center",
                margin: 10,
              }}
            >
              <Icon type="PlusCircle" />
            </div>
          </div>
        }
      />
      <Drawer
        width={(window.innerWidth / 100) * 50}
        title={store.titleDrawer}
        destroyOnClose={true}
        onClose={() => store.editDrawer(DrawersSkill.EDIT_SKILL, false)}
        open={store.drawers.find((el) => el.name === DrawersSkill.EDIT_SKILL)?.status}
      >
        <div style={{ display: "flex", flexDirection: "column", justifyContent: "space-between", height: "100%" }}>
          <FormBuilder
            formBuilder={store.editProcess?.formBuilder ?? FormBuilderValidationModel.empty()}
            onChange={(formBuilder) => store.updateForm({ formBuilder: formBuilder })}
          />

          <div style={{ display: "flex" }}>
            <CoreButton text="Сохранить" filled={true} onClick={() => store.saveEdiSkill()} />
            <div style={{ width: 10 }} />
            <CoreButton text="Отмена" onClick={() => store.editDrawer(DrawersSkill.EDIT_SKILL, false)} />
          </div>
        </div>
      </Drawer>
      <Drawer
        width={(window.innerWidth / 100) * 50}
        title={store.titleDrawer}
        destroyOnClose={true}
        afterOpenChange={() => store.selectType(StoreTypes.empty)}
        onClose={() => store.editDrawer(DrawersSkill.NEW_SKILL, false)}
        open={store.drawers.find((el) => el.name === DrawersSkill.NEW_SKILL)?.status}
      >
        <div style={{ display: "flex", flexDirection: "column", justifyContent: "space-between", height: "100%" }}>
          <div>
            {match(store.storeType)
              .with(StoreTypes.empty, () => (
                <>
                  <CoreText
                    text={"Создать новый тип процесса"}
                    type={CoreTextType.header}
                    onClick={() => store.selectType(StoreTypes.newType)}
                  />
                  <CoreText
                    text={"Создать новый инстанц процесса"}
                    type={CoreTextType.header}
                    onClick={() => store.selectType(StoreTypes.newModel)}
                  />
                </>
              ))
              .with(StoreTypes.newType, () => (
                <>
                  <CoreSelect
                    items={Object.keys(ModelMachineLearningTypes)}
                    value={store.viewModel.type}
                    label={"Тип навыка"}
                    onChange={(text: string) => store.updateForm({ type: text })}
                  />
                  <CoreSelect
                    items={Object.keys(CardModel)}
                    value={""}
                    label={"Тип карточки"}
                    onChange={(text: string) => store.updateForm({ card: text })}
                  />
                  <CoreInput label="Имя" onChange={(text) => store.updateForm({ name: text })} />
                  <CoreInput label="Команда для запуска" onChange={(text) => store.updateForm({ script: text })} />
                  <InputV2
                    label="FormBuilder Result"
                    onChange={(text) => (store.viewModel.formBuilder.result = text)}
                    // style={{ height: 200, overflow: "overlay" }}
                  />
                  <InputV2
                    label="FormBuilder Context"
                    onChange={(text) => (store.viewModel.formBuilder.context = text)}
                    // style={{ height: 200, overflow: "overlay" }}
                  />
                  <div style={{ height: 10 }} />
                  <CoreButton
                    style={{ width: 206 }}
                    text={"Посмотреть FormBuilder "}
                    onClick={() => (store.isModalOpen = true)}
                  />
                  <div style={{ height: 10 }} />
                </>
              ))
              .with(StoreTypes.newModel, () => (
                <div>
                  <CoreInput
                    label={"Имя инстанца вычисления"}
                    onChange={(text) => store.updateForm({ instanceName: text })}
                  />
                  <div style={{ width: "100%", display: "grid", gridTemplateColumns: "repeat(3, 240px)" }}>
                    {store.modelTemplate?.map((el, i) => (
                      <>
                        <TemplateModelCard
                          key={i}
                          model={el}
                          isSelect={store.selectTemplate?.name.isEqual(el.name) ?? false}
                          onDelete={() => store.deleteTemplate(el)}
                          onClick={() => store.setSelectTemplate(el)}
                        />
                      </>
                    ))}
                  </div>
                </div>
              ))
              .otherwise(() => (
                <></>
              ))}
          </div>
          <div style={{ display: "flex" }}>
            <CoreButton text="Сохранить" filled={true} onClick={() => store.clickSave()} />
            <div style={{ width: 10 }} />
            <CoreButton text="Отмена" onClick={() => store.editDrawer(DrawersSkill.NEW_SKILL, false)} />
          </div>
        </div>
      </Drawer>
      <Modal
        destroyOnClose={true}
        open={store.isModalOpen}
        footer={null}
        closable={false}
        closeIcon={null}
        onCancel={() => {
          store.isModalOpen = false;
        }}
      >
        <FormBuilder formBuilder={store.viewModel.formBuilder} onChange={() => {}} />
      </Modal>
    </>
  );
});
