<script setup>
import SettingsTab from "@/layouts/SettingsTab.vue";
import MdrFormField from "@/components/Mudur-Ui-Kit/MdrFormField.vue";
import PrimaryButton from "@/components/Buttons/PrimaryButton.vue";
import DangerButton from "@/components/Buttons/DangerButton.vue";
import { storeToRefs } from "pinia";
import { useSettingsStore } from "@/stores/SettingsStore";
import { useResourceStore } from "@/stores/ResourceStore";
import { ref } from "vue";

const { saveApiKey, deleteApiKey, syncOptions } = useSettingsStore();
const { invoiceIntegrations } = storeToRefs(useResourceStore());
const show = ref(false);

const { apiKey } = storeToRefs(useSettingsStore());

const {
  profile,
  api_key: currentApiKey,
  ginvoice_env: ginvoiceEnv,
  ginvoice_connect_url: ginvoiceConnectUrl,
  ginvoice_webhook_url: ginvoiceWebhookUrl,
  last_sync: lastSyncTimeRef,
} = window.ginvoice;

const lastSyncTime = ref(lastSyncTimeRef);

const sync = async () => {
  const response = await syncOptions();
  invoiceIntegrations.value = response.invoice_integrations;
  lastSyncTime.value = response.last_sync;
};

const connect = () => {
  window.location.href = `https://${ginvoiceEnv}.faturaentegrator.com/api-key?redirect_url=${ginvoiceConnectUrl}&webhook_url=${ginvoiceWebhookUrl}`;
};

const secretEmail = (email) => {
  const [name, domain] = email.split("@");

  if (name.length <= 2) return email;

  const first = name[0];
  const last = name[name.length - 1];

  const stars = "*".repeat(name.length - 2);

  return `${first}${stars}${last}@${domain}`;
};
</script>
<template>
  <SettingsTab>
    <template #title>
      {{ $t("connection") }}
    </template>
    <template #description>
      {{ $t("connection_top", ["Fatura Entegratör"]) }}
    </template>

    <div v-if="!currentApiKey" class="flex items-center gap-2">
      <PrimaryButton @click="connect">Şimdi Bağlantı Kur</PrimaryButton>
      yada
      <span
        class="text-primary-600 underline cursor-pointer"
        @click="show = true"
        >API anahtarı kaydet</span
      >
    </div>

    <div v-if="show || currentApiKey" class="flex flex-col gap-3 mt-4">
      <MdrFormField v-model="apiKey" :label="$t('api_key')" class="!w-1/2" />
      <div v-if="!currentApiKey">
        <PrimaryButton class="max-w-fit" @click="saveApiKey(apiKey)">
          {{ $t("save") }}
        </PrimaryButton>
        <div class="text-sm mt-2 flex items-center gap-1">
          {{ $t("not_api_key") }}
          <a
            class="underline text-primary-600"
            href="https://app.faturaentegrator.com"
            target="_blank"
            >{{ $t("sign_up_now") }}</a
          >
        </div>
      </div>
      <div v-else class="flex flex-col gap-2">
        <div class="flex gap-2 items-center">
          <DangerButton class="max-w-fit" @click="deleteApiKey">
            {{ $t("disconnect") }}
          </DangerButton>
          <PrimaryButton @click="sync"> Senkronize Et </PrimaryButton>
          <span class="text-green-600 font-medium"
            >✅ {{ $t("api_key_success") }}</span
          >
        </div>
        <span v-if="lastSyncTime" class="text-sm text-gray-500">
          Son Senkronizasyon: {{ lastSyncTime }}
        </span>
        <span v-if="profile?.team?.owner?.email" class="text-sm text-gray-500">
          {{ secretEmail(profile?.team?.owner?.email) }}
        </span>
        <a
          href="https://app.faturaentegrator.com"
          target="_blank"
          class="text-sm text-blue-600 underline"
        >
          Uygulamaya git
        </a>
      </div>
    </div>
  </SettingsTab>
</template>
