import { makeAutoObservable } from 'mobx';
import React from 'react';

/**
 * Interface for a Tab view state
 */
export interface UITabView {
  /**
   * The id of the current selected tab in the tab view.
   * @optional
   * @default first tab in the view will be the selected one
   */
  selectedId?: string | undefined;
  /**
   * The unique id for this tab view.
   * It is a global id for this tab view.
   */
  id: string;
  /**
   * The list of options for this tab.
   */
  tabs?: UITabViewOption[];
}
/**
 * Interface for one tab option.
 */
export interface UITabViewOption {
  /**
   * Unique id for the tab.
   * Must be unique across all tabs, if used in a tab group.
   */
  id: string;
  /**
   * The label of the tab.
   */
  label: string;
  /**
   * The index of the tab.
   * @optional
   * @default undefined
   */
  index?: number;
  /**
   * The action to be called when the tab is selected.
   * @returns void
   */
  action?: () => void;
  /**
   * This is added for convenience.
   * However, if using a react component, it will make this tab not
   * configurable via json.
   * @optional use with caution
   */
  content?: React.ReactNode;
}
/**
 * A model to handle tabs in the app.
 */
export class TabViewModel {
  id: string;
  selectedId: string | undefined;
  tabs: UITabViewOption[];

  constructor(tab: UITabView) {
    this.id = tab.id; // unique id for this tab
    this.selectedId = tab.selectedId;
    this.tabs = tab.tabs || [];
    makeAutoObservable(this);
  }

  get content(): React.ReactNode | null {
    if (!this.selectedId) {
      return null;
    }
    return this.tabs.find((option) => option.id === this.selectedId)?.content;
  }

  setSelectedId = (value?: string | undefined) => {
    this.selectedId = value;
  };

  setTabs = (tabs: UITabViewOption[]) => {
    this.tabs = tabs;
  };

  onSelected = (id: string) => {
    this.setSelectedId(id);
  };
}
