function handlerDynamicTabs(target, name, value) {

  if (name === 'value') {
    const oldValue = target.value;
    const isAdding = value.length - oldValue.length > 0;
    const activeIndex = !isAdding ? target.tabs.findIndex(item => item.active) : null;

    target.tabs = value.map((item, index) => ({
      text: item[target['tabText']],
      active: Number.isInteger(activeIndex) ? index === activeIndex : index === 0,
    }));
  }

  target[name] = value;

  return true;
}

class DynamicTabs {
  constructor(tabText = 'text') {
    this.tabText = tabText;
    this.value = [];
    this.tabs = [];

    const proxy = new Proxy(this, {
      set: handlerDynamicTabs,
    });

    this.watch = {
      deep: true,
      handler: function (value) {
        proxy.value = value;
        this.$emit('updatedvalue', value);
      }
    };

    this.computed = () => {
      return proxy.tabs;
    };

    return proxy;
  }

  static clickTab(tab, value) {
    this[tab].tabs = value;
  }
}

export default function getDynamicTabsMixin() {
  const data = {};
  const mixin = {
    watch: {},
    computed: {},
    methods: {
      clickDynamicTab: DynamicTabs.clickTab,
    },
  };

  const args = Array.from(arguments);

  for (let i = 0; i < args.length; i++) {
    const { name, title } = args[i];
    const dynamicTabs = new DynamicTabs(title);

    data[name] = dynamicTabs;
    mixin.watch[`${name}`] = dynamicTabs.watch;
    mixin.computed[`${name}Tabs`] = dynamicTabs.computed;
  }

  mixin.data = function() {
    return data;
  };

  return mixin;
}
