<template>
  <div class="q-pa-md" style="max-width: 450px">
    <q-form @submit="onSubmit" class="flex items-center">
      <q-input
        v-model="apiKey"
        class="q-pa-none q-ma-none col"
        label="Google Sheets API key"
        lazy-rules
        filled
        dense
        :type="isPassword ? 'password' : 'text'"
        :loading="loading"
        :disable="loading"
        :readonly="apiKeySaved"
        :rules="[
          (val) =>
            (val && val.length > 3) ||
            $t('messages.please_paste_your_google_sheets_api_key'),
        ]"
      >
        <template #append>
          <q-icon
            :name="isPassword ? 'visibility_off' : 'visibility'"
            class="cursor-pointer"
            @click="isPassword = !isPassword"
          />
        </template>
      </q-input>

      <q-btn
        v-if="apiKeySaved"
        class="q-ma-none q-ml-md"
        :disable="loading"
        :loading="loading"
        :label="$t('remove')"
        type="reset"
        color="red-7"
        push
        @click="onRemove"
      />

      <q-btn
        v-else
        class="q-ma-none q-ml-md"
        :disable="loading"
        :loading="loading"
        :label="$t('save')"
        type="submit"
        color="primary"
        push
      />
    </q-form>

    <p class="q-mt-md">
      <q-icon class="q-mr-sm" name="info_outline" size="xs">
        <q-tooltip
          anchor="center right"
          self="center left"
          :offset="[10, 10]"
          max-width="250px"
        >
          {{ $t('messages.we_recommend_obtaining_google_sheets_api_key') }}
        </q-tooltip>
      </q-icon>
      <a
        href="https://console.cloud.google.com/apis/credentials"
        target="_blank"
        rel="noopener noreferrer"
      >
        {{ $t('get_api_key') }}
      </a>
    </p>
  </div>
</template>

<script setup lang="ts">
import { useQuasar } from 'quasar';
import { wpMenuHelper } from 'src/helpers/wpMenuHelper';
import { Ref, ref } from 'vue';
import { useMainStore } from 'src/stores/main';
import { REMOVE_API_KEY, SAVE_API_KEY } from 'src/stores/main/constants';
import { storeToRefs } from 'pinia';

/**
 * STORE
 */
const mainStore = useMainStore();
const saveApiKey = mainStore[SAVE_API_KEY];
const removeApiKey = mainStore[REMOVE_API_KEY];
const { apiKey, apiKeySaved, isAdminPage } = storeToRefs(mainStore);

/**
 * CONSTANTS
 */
const $q = useQuasar();
const loading: Ref<boolean> = ref(false);
const isPassword: Ref<boolean> = ref(true);

/**
 * LIFE-CYCLE HOOK: CREATED
 */
(async () => {
  if (isAdminPage.value) {
    wpMenuHelper('settings');
  }
})();

/**
 * ON SUBMIT
 */
async function onSubmit() {
  loading.value = true;
  const { response, error } = await saveApiKey(apiKey.value);
  loading.value = false;

  if (error) {
    const message =
      error.data.message || 'Something went wrong, please try again later.';

    $q.notify({
      type: 'negative',
      icon: 'warning',
      message,
    });

    return;
  }

  if (response?.data) {
    apiKeySaved.value = true;
  }

  $q.notify({
    type: 'positive',
    icon: 'done',
    message: 'Your API key has been added.',
  });
}

/**
 * ON REMOVE
 */
async function onRemove() {
  loading.value = true;
  const { error } = await removeApiKey();
  loading.value = false;

  if (error) {
    const message =
      error.data.message || 'Something went wrong, please try again later.';

    $q.notify({
      type: 'negative',
      icon: 'warning',
      message,
    });

    return;
  }

  apiKey.value = '';
  apiKeySaved.value = false;

  $q.notify({
    type: 'positive',
    icon: 'done',
    message: 'Your API key has been removed.',
  });
}
</script>
