import AdmVue from '@assets/js/adm-vue.js';
import { v4 as uuidv4, validate } from 'uuid';

const vm = new AdmVue({
  components: {
    BaseCard: () => import(/* webpackChunkName: "BaseCard" */ '@elements/BaseCard/index.vue'),
    HighlightEditor: () => import(/* webpackChunkName: "HighlightEditor" */ '@components/HighlightEditor/index.vue'),
    AsideContent: () => import(/* webpackChunkName: "AsideContent" */ '@components/AsideContent/index.vue'),
    BaseTabs: () => import(/* webpackChunkName: "BaseTabs" */ '@components/BaseTabs/index.vue'),
  },
  data() {
    return {
      tabsCode: [],
      tracking_code: [],
      showLastCode: false,
      showNewCodeScreen: false,
      excluded: [],
      presets: ['Google Analytics', 'Google Tag Manager'],
    };
  },
  computed: {
    sendData() {
      const tracking_code = this.tracking_code.map(trackingCodeItem => {
        if (validate(trackingCodeItem.tracking_code_id)) {
          delete trackingCodeItem.tracking_code_id;
        }
        return trackingCodeItem;
      });

      return {
        tracking_code,
        excluded: [...this.excluded],
      };
    },
    indexActiveCode() {
      return this.tabsCode.findIndex(item => item.active);
    },
    activeCode() {
      if (this.indexActiveCode) {
        return this.tracking_code[this.indexActiveCode];
      }

      if (typeof this.tracking_code[0] !== 'undefined') {
        return this.tracking_code[0];
      }

      return {};
    },
    infoCode() {
      switch (this.activeCode.title) {
        case 'Google Analytics':
          return `
            Crie uma conta e uma propriedade no Google Analytics 4. Copie e cole o código gerado. Deixe esse código em todas as páginas e no cabeçalho<br>
            Para mais informações acesse os <a class="text-info text-small text-bold" href="https://developers.google.com/analytics/devguides/collection/ga4" target="_blank">Adicionar o Google Analytics G4</a>.
          `;

        case 'Google Tag Manager':
          return `
            Copie e cole apenas o primeiro código do Google Tag Manager. Ignore o código do Google Tag Manager (noscript). Deixe esse código em todas as páginas e no cabeçalho<br>
            Para mais informações acesse <a class="text-info text-small text-bold" href="https://developers.google.com/tag-manager/quickstart" target="_blank">Guia de início rápido</a> do Google Tag Manager.
          `;

        default:
          return '';
      }
    },
    buttonPresets() {
      return this.presets.filter(presetsItem => {
        if (this.tracking_code.find(trackingCodeItem => trackingCodeItem.title === presetsItem)) {
          return;
        }
        return presetsItem;
      });
    },
  },
  watch: {
    tracking_code: {
      handler(value) {
        if (!value.length) {
          this.tabsCode = [];
          return;
        }

        let active = this.activeCode
          ? value.findIndex(item => item.tracking_code_id === this.activeCode.tracking_code_id)
          : 0;

        if (this.showLastCode) {
          this.showLastCode = false;
          active = value.length - 1;
        }

        this.tabsCode = value.map((trackingCodeItem, trackingCodeIndex) => {
          return {
            text: trackingCodeItem.title,
            active: trackingCodeIndex === active,
          };
        });
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    onPrimaryAdd() {
      const hasEmptyScript = this.tracking_code.find(
        trackingCodeItem => trackingCodeItem.script === '' || trackingCodeItem.title === ''
      );

      if (hasEmptyScript) {
        this.alert = {
          type: 'error',
          message: 'Termine o código antes de criar um novo.',
        };
        this.showNewCodeScreen = false;
        return;
      }

      if (this.buttonPresets.length > 0) {
        this.showNewCodeScreen = true;
      } else {
        this.onAdd('Novo código');
      }
    },
    onAdd(preset) {
      const trackingCode = {
        tracking_code_id: uuidv4(),
        title: preset,
        all_layouts: 1,
        position: 1,
        script: '',
        status: 1,
      };

      if(this.presets.find(presetItem => presetItem === trackingCode.title) &&
        this.tracking_code.filter(trackingCodeItem => {
          return this.presets.find(presetItem => presetItem === trackingCodeItem.title);
        }).length > 0) {
        this.alert = {
          type: 'warning',
          message: 'Google Tag Manager e Analytics juntos, pode gerar duplicidade nos dados dos relatórios!',
        };
      }

      this.tracking_code.push(trackingCode);

      this.showLastCode = true;
      this.showNewCodeScreen = false;
    },
    onRemove() {
      if (!validate(this.activeCode.tracking_code_id)) {
        this.setExcludedIds(this.activeCode.tracking_code_id);
      }

      const activeIndexCode = this.tracking_code.findIndex(
        trackingCodeItem => trackingCodeItem.tracking_code_id === this.activeCode.tracking_code_id
      );

      if (activeIndexCode === this.tracking_code.length - 1) {
        this.showLastCode = true;
      }

      this.tracking_code.splice(activeIndexCode, 1);
    },
    setExcludedIds(tracking_code_id) {
      if (typeof tracking_code_id !== 'undefined') {
        this.excluded = [...this.excluded, tracking_code_id];
      }
    },
    formSuccess({ list }) {
      this.tracking_code = list;
    },
    onClickTab(tabs) {
      this.tabsCode = tabs;
    },
  },
});

AdmVue.init(vm);
