import { onWillUpdateProps, proxy, signal, useProps } from "@odoo/owl";
import { DEFAULT_BORDER_DESC } from "../../constants";
import { Component } from "../../owl3_compatibility_layer";
import { useStore } from "../../store_engine/store_hooks";
import { ViewportsStore } from "../../stores/viewports_store";
import { BorderPosition, BorderStyle, Color, Pixel } from "../../types/misc";
import { Rect } from "../../types/rendering";
import { SpreadsheetChildEnv } from "../../types/spreadsheet_env";
import { Store } from "../../types/store_engine";
import { getElBoundingRect } from "../helpers/dom_helpers";
import { ToolBarDropdownStore, useToolBarDropdownStore } from "../helpers/top_bar_tool_hook";
import { types } from "../props_validation";
import { BorderEditor } from "./border_editor";

interface State {
  currentColor: Color;
  currentStyle: BorderStyle;
  currentPosition: BorderPosition | undefined;
}

export class BorderEditorWidget extends Component<SpreadsheetChildEnv> {
  static template = "o-spreadsheet-BorderEditorWidget";
  static components = { BorderEditor };

  protected props = useProps({
    disabled: types.boolean().optional(),
    dropdownMaxHeight: types.Pixel().optional(),
    class: types.string().optional(),
  });
  topBarToolStore!: ToolBarDropdownStore;
  private viewStore!: Store<ViewportsStore>;

  borderEditorButtonRef = signal.ref();
  state: State = proxy({
    currentColor: DEFAULT_BORDER_DESC.color,
    currentStyle: DEFAULT_BORDER_DESC.style,
    currentPosition: undefined,
  });

  setup() {
    this.topBarToolStore = useToolBarDropdownStore();
    this.viewStore = useStore(ViewportsStore);
    onWillUpdateProps(() => {
      if (!this.isActive) {
        this.state.currentPosition = undefined;
      }
    });
  }

  get dropdownMaxHeight(): Pixel {
    return this.viewStore.sheetViewDimension.height;
  }

  get borderEditorAnchorRect(): Rect {
    return getElBoundingRect(this.borderEditorButtonRef());
  }

  onBorderPositionPicked(position: BorderPosition) {
    this.state.currentPosition = position;
    this.updateBorder();
  }

  onBorderColorPicked(color: Color) {
    this.state.currentColor = color;
    this.updateBorder();
  }

  onBorderStylePicked(style: BorderStyle) {
    this.state.currentStyle = style;
    this.updateBorder();
  }

  get isActive(): boolean {
    return this.topBarToolStore.isActive;
  }

  toggleBorderEditor() {
    if (this.isActive) {
      this.topBarToolStore.closeDropdowns();
    } else {
      this.topBarToolStore.openDropdown();
    }
  }

  private updateBorder() {
    if (this.state.currentPosition === undefined) {
      return;
    }
    this.env.model.dispatch("SET_ZONE_BORDERS", {
      sheetId: this.env.model.getters.getActiveSheetId(),
      target: this.env.model.getters.getSelectedZones(),
      border: {
        position: this.state.currentPosition,
        color: this.state.currentColor,
        style: this.state.currentStyle,
      },
    });
  }
}
