// @ts-nocheck

import { TreeNode } from 'src/types/stores/kanvaso';
import { COLOR_LIGHT, COLOR_PRIMARY, COLOR_DARK } from './Const';
import { DefaultDepth, DragObjectDepth } from './Const';
import CreateItemsBox from '../cards/CreateItemsBox';

type DialogFunction = (config: any) => any;
type RoundRectangleFunction = (config: any) => any;
type LabelFunction = (config: any) => any;
type TextFunction = (x: number, y: number, text: string, style: any) => any;

type SceneType = {
  rexUI: {
    add: {
      dialog: DialogFunction;
      roundRectangle: RoundRectangleFunction;
      label: LabelFunction;
    };
  };
  add: {
    text: TextFunction;
  };
};

const CreateColumnPanel = (
  scene: SceneType,
  column: TreeNode,
  registry: Phaser.Data.DataManager,
) => {
  const panel = scene.rexUI.add
    .dialog({
      width: 120,
      space: { left: 10, right: 10, top: 10, bottom: 10 },
      background: scene.rexUI.add.roundRectangle({
        strokeColor: COLOR_DARK,
      }),
      title: CreateTitle(scene, column, registry),
      content: CreateItemsBox(
        scene,
        column.childrens ? column.childrens : [],
        registry,
      ),
      proportion: {
        content: 1,
      },
    })
    .setOrigin(0, 0);

  SetDraggable(panel);

  return panel;
};

const CreateTitle = (
  scene: SceneType,
  column: TreeNode,
  registry: Phaser.Data.DataManager,
) => {
  const title = scene.rexUI.add.label({
    background: scene.rexUI.add.roundRectangle({
      color: COLOR_LIGHT,
    }),
    text: scene.add.text(0, 0, column.name || '', {
      fontSize: 18,
    }),
    align: 'left',
    space: {
      left: 5,
      right: 5,
      top: 5,
      bottom: 5,
    },
  });

  registry.events.on('changedata', (parent, key, data, previousData) => {
    if (data.uuid === column.uuid) {
      title.setText(data.name);
    }
  });

  return title;
};

const SetDraggable = (panel: any) => {
  panel
    .setDraggable({
      sensor: 'title',
      target: panel,
    })
    .on('sizer.dragstart', OnPanelDragStart, panel)
    .on('sizer.dragend', OnPanelDragEnd, panel);
};

const OnPanelDragStart = function (this: any) {
  this.setDepth(DragObjectDepth);
  this.getElement('background').setStrokeStyle(3, 0xff0000);
};

const OnPanelDragEnd = function (this: any) {
  this.setDepth(DefaultDepth);
  this.getElement('background').setStrokeStyle(2, COLOR_DARK);
};

export default CreateColumnPanel;
