import router from '@/vue/router';
import { browser } from 'wxt/browser';
import { getCurrentUrl } from '@/browser/tab';
import {
  shopeeUrlMatchProductId,
  shopeeUrlMatchSearch,
  shopeeUrlMatchShopUsername,
  tiktokUrlMatchProductId,
  tiktokUrlMatchSellerPrint,
  shopeeUrlMatchSellerPrint,
  lazadaUrlMatchSellerPrint,
} from '@/lib/match';
import { getShopeeShopByUsername } from '@/api/shopee/client/shop';

const routerTo = {
  root: '/',
  login: '/login',
  register: '/register',
  setting: '/setting',
  contact: '/contact',
  shopee: '/shopee',
  app: '/app',
  flashsaleIndex: '/shopee/seller/flashsale',
  flashsaleCreate: '/shopee/seller/flashsale/create',
  printerPopup: '/printer/popup',
};

/** @type {VuexStoreModule} */
export const routerStore = {
  state() {
    return {
      current: {
        name: '',
        path: '',
        meta: '',
      },
      history: {
        name: '',
        path: '',
        meta: '',
      },
    };
  },
  mutations: {
    SET_ROUTER_CURRENT(state, data) {
      state.current = data;
    },
    SET_ROUTER_HISTORY(state, data) {
      state.history = data;
    },
  },
  getters: {
    getRouterCurrent(state) {
      return state.current;
    },
    getRouterHistory(state) {
      return state.history;
    },
    getRouterUrl() {
      return (uri) => {
        return `${window.location.origin}/popup.html#${uri}`;
      };
    },
  },
  actions: {
    SetRouterCurrent({ commit }, data) {
      commit('SET_ROUTER_CURRENT', data);
    },
    SetRouterHistory({ commit }, data) {
      commit('SET_ROUTER_HISTORY', data);
    },
    async RouterBack() {
      return router.go(-1);
    },
    async RouterLogin({}, returnUrl) {
      return router.push({
        path: '/login',
        query: {
          returnUrl,
        },
      });
    },
    async RouterTo({ dispatch }, name) {
      const path = routerTo[name];

      return dispatch('RouterPath', path);
    },
    async Router404() {
      return router.push('/404');
    },
    async RouterInit() {
      const url = await getCurrentUrl();
      const [tabData] = await browser.tabs.query({ active: true, currentWindow: true });
      const tabId = tabData.id;

      if (routerTo.printerPopup) {
        if (shopeeUrlMatchSellerPrint(url)) {
          return router.push({
            path: routerTo.printerPopup,
            query: {
              ...shopeeUrlMatchSellerPrint(url),
              fromTabId: tabId,
            },
          });
        }

        if (tiktokUrlMatchSellerPrint(url)) {
          return router.push({
            path: routerTo.printerPopup,
            query: {
              ...tiktokUrlMatchSellerPrint(url),
              fromTabId: tabId,
            },
          });
        }

        if (lazadaUrlMatchSellerPrint(url)) {
          return router.push({
            path: routerTo.printerPopup,
            query: {
              ...lazadaUrlMatchSellerPrint(url),
              fromTabId: tabId,
            },
          });
        }

        if (url.endsWith('.pdf')) {
          return router.push({
            path: routerTo.printerPopup,
            query: {
              from: 'url',
              jobUrl: url,
              fromTabId: tabId,
            },
          });
        }
      }

      if (shopeeUrlMatchSearch(url)) {
        const { keyword } = shopeeUrlMatchSearch(url);
        return router.push({
          path: '/shopee/spy/search',
          query: {
            keyword,
          },
        });
      }

      if (shopeeUrlMatchShopUsername(url)) {
        const { username } = shopeeUrlMatchShopUsername(url);
        const shopData = await getShopeeShopByUsername(username).catch(() => null);

        if (shopData && shopData.shopid) {
          return router.push({
            path: `/shopee/spy/shop/${shopData.shopid}`,
          });
        }
      }

      if (shopeeUrlMatchProductId(url)) {
        const { productId, shopId } = shopeeUrlMatchProductId(url);
        return router.push({
          path: '/shopee/product/clone',
          query: {
            productId,
            shopId,
          },
        });
      }

      if (tiktokUrlMatchProductId(url)) {
        const { productId } = tiktokUrlMatchProductId(url);
        return router.push({
          path: `/tiktok/product/clone/${productId}`,
        });
      }

      return null;
    },
    async RouterPath({}, path) {
      await router
        .push({
          path,
        })
        .catch(() => {});

      return path;
    },
  },
};
