<template>
  <q-page class="q-mr-md q-mt-md">
    <template v-if="isAdminPage && selectedTable">
      <!-- GO BACK -->
      <div class="row q-mb-md">
        <div class="col flex items-center">
          <q-btn
            icon="keyboard_backspace"
            color="grey-8"
            outline
            @click="goBack"
          >
            <span class="q-pl-xs">{{ $t('back') }}</span>
          </q-btn>
        </div>
        <div class="col flex items-center justify-end" style="gap: 10px">
          <TheTableShortcode :shortcode="selectedTable.shortcode" />
          <q-btn-dropdown color="primary" icon="menu" unelevated>
            <q-list>
              <q-item clickable v-close-popup @click="open">
                <q-item-section side>
                  <q-icon name="open_in_new" />
                </q-item-section>
                <q-item-section>
                  <q-item-label>{{ $t('open_in_google_sheets') }}</q-item-label>
                </q-item-section>
              </q-item>

              <q-item clickable v-close-popup @click="fetchRemoteSource">
                <q-item-section side>
                  <q-icon name="sync" />
                </q-item-section>
                <q-item-section>
                  <q-item-label>{{ $t('sync_data') }}</q-item-label>
                </q-item-section>
              </q-item>

              <q-item
                clickable
                v-close-popup
                @click="deleteHandler(selectedTable.id)"
              >
                <q-item-section side>
                  <q-icon name="delete" color="red-10" />
                </q-item-section>
                <q-item-section>
                  <q-item-label class="text-red-10">
                    {{ $t('delete') }}
                  </q-item-label>
                </q-item-section>
              </q-item>
            </q-list>
          </q-btn-dropdown>
        </div>
      </div>
    </template>
    <TheTable />
  </q-page>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { Router, useRouter } from 'vue-router';
import { useMainStore } from 'src/stores/main';
import TheTable from 'src/components/TheTable.vue';
import { getSheetIdFromString } from 'src/helpers/getSheetIdFromStringHelper';
import { useQuasar } from 'quasar';
import { useI18n } from 'vue-i18n';
import {
  DELETE_TABLE_BY_ID,
  FETCH_REMOTE_TABLE,
  SYNC_TABLE_CONTENT,
} from 'src/stores/main/constants';
import TheTableShortcode from 'src/components/TheTableShortcode.vue';

/**
 * DASHBOARD STORE
 */
const mainStore = useMainStore();
const fetchRemoteTable = mainStore[FETCH_REMOTE_TABLE];
const syncTableContent = mainStore[SYNC_TABLE_CONTENT];
const deleteTableById = mainStore[DELETE_TABLE_BY_ID];
const { loading, selectedTable, isAdminPage } = storeToRefs(mainStore);

/**
 * CONSTANTS
 */
const $q = useQuasar();
const { t } = useI18n();
const router: Router = useRouter();

/**
 * GO BACK
 */
function goBack() {
  selectedTable.value = null;
  router.push('/');
}

/**
 * FETCH REMOTE SOURCE
 */
async function fetchRemoteSource() {
  if (!selectedTable.value?.source) {
    return;
  }

  const sheetId = getSheetIdFromString(selectedTable.value.source);

  if (!sheetId) {
    $q.notify({
      type: 'negative',
      message: t('messages.cant_extract_sheet_id'),
    });

    return;
  }

  loading.value = true;

  const { response, error } = await fetchRemoteTable(sheetId);

  if (error || !response) {
    loading.value = false;
    return;
  }

  const rows = response.data as Record<string | number | symbol, unknown>[];

  const content = {
    columns: [],
    rows,
  };

  const syncTableContentResult = await syncTableContent({
    id: selectedTable.value.id,
    title: selectedTable.value.title,
    content,
  });

  if (syncTableContentResult.error) {
    loading.value = false;
    return;
  }

  if (syncTableContentResult?.response?.data?.content) {
    selectedTable.value.content = syncTableContentResult.response.data.content;

    $q.notify({
      type: 'positive',
      message: t('messages.data_has_been_synced'),
    });
  }

  loading.value = false;
}

/**
 * OPEN G.SHEET URL
 */
function open() {
  if (selectedTable.value?.source) {
    const windowObj: any = window;
    windowObj.open(selectedTable.value.source, '_blank').focus();
  }
}

/**
 * DELETE TABLE HANDLER
 * @param id
 */
function deleteHandler(id: string) {
  $q.dialog({
    title: 'Confirm',
    message: 'Delete this table?',
    cancel: true,
    ok: {
      label: 'Confirm',
    },
  }).onOk(async () => {
    await onDelete(id);
  });
}

/**
 * ON DELETE
 * @param id
 */
async function onDelete(id: string) {
  loading.value = true;
  await deleteTableById(id);
  loading.value = false;
  router.push('/');
}
</script>

<style scoped>
.q-list .q-item {
  border-bottom: 1px dotted #c1c1c1;
}
</style>
