import { onWillUpdateProps, proxy, useProps } from "@odoo/owl";
import { getPivotHighlights } from "../../../../helpers/pivot/pivot_highlight";
import { pivotSidePanelRegistry } from "../../../../helpers/pivot/pivot_side_panel_registry";
import { Component } from "../../../../owl3_compatibility_layer";
import { PropsOf } from "../../../../types/props_of";
import { SpreadsheetChildEnv } from "../../../../types/spreadsheet_env";
import { useHighlights } from "../../../helpers/highlight_hook";
import { types } from "../../../props_validation";
import { Section } from "../../components/section/section";
import { PivotLayoutConfigurator } from "../pivot_layout_configurator/pivot_layout_configurator";
import { PivotDesignPanel } from "./pivot_design_panel/pivot_design_panel";

interface State {
  panel: "configuration" | "design";
}

export class PivotSidePanel extends Component<SpreadsheetChildEnv> {
  static template = "o-spreadsheet-PivotSidePanel";
  static components = {
    PivotLayoutConfigurator,
    Section,
    PivotDesignPanel,
  };

  protected props = useProps({
    pivotId: types.UID(),
    onCloseSidePanel: types.function(),
    openTab: types
      .or([types.literal("configuration"), types.literal("design")])
      .optional("configuration"),
  });

  state = proxy<State>({ panel: this.props.openTab || "configuration" });

  setup() {
    useHighlights(this);
    onWillUpdateProps((nextProps: PropsOf<PivotSidePanel>) => {
      if (nextProps.openTab && nextProps.openTab !== this.props.openTab) {
        this.switchPanel(nextProps.openTab);
      }
    });
  }

  get sidePanelEditor() {
    const pivot = this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);
    if (!pivot) {
      throw new Error("pivotId does not correspond to a pivot.");
    }
    return pivotSidePanelRegistry.get(pivot.type).editor;
  }

  get highlights() {
    return this.state.panel === "configuration"
      ? getPivotHighlights(this.env, this.props.pivotId)
      : [];
  }

  switchPanel(panel: "configuration" | "design") {
    this.state.panel = panel;
  }
}
