<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 Plan from "../Partials/Plan.vue";
import ApiError from "../Partials/ApiError.vue";
import { useResourceStore } from "@/stores/ResourceStore";
import { useApiRequestStore } from "@/stores/ApiRequestStore";
import { ref, onMounted } from "vue";

const { saveApiKey, deleteApiKey } = useSettingsStore();
const { syncOptions } = useApiRequestStore();
const { apiKey, shipmentSetting, returnedSetting } =
  storeToRefs(useSettingsStore());
const { warehouses, cargoIntegrations } = storeToRefs(useResourceStore());
const { accountDetails } = useSettingsStore();
const currentApiKey = window.gcargo.api_key;
const gcargoEnv = window.gcargo.gcargo_env;
const gcargoConnectUrl = window.gcargo.gcargo_connect_url;
const gcargoWebhookUrl = window.gcargo.gcargo_webhook_url;
const show = ref(false);

const updateKey = async () => {
  await saveApiKey(apiKey.value);
  wcButton[0].click();
};
const lastSyncTime = ref(null);

const sync = async () => {
  const response = await syncOptions();
  lastSyncTime.value = response.last_sync;
  warehouses.value = response.warehouses;
  cargoIntegrations.value = response.cargo_integrations;
  shipmentSetting.value = response.shipment_setting;
  returnedSetting.value = response.returned_setting;
};

onMounted(() => {
  lastSyncTime.value = window.gcargo.last_sync_time;
});

const wcButton = document.getElementsByClassName("is-primary");

const connect = () => {
  window.location.href = `https://${gcargoEnv}.kargoentegrator.com/api-key?redirect_url=${gcargoConnectUrl}&webhook_url=${gcargoWebhookUrl}`;
};

const goToSaas = () => {
  window.open(
    `https://${gcargoEnv}.kargoentegrator.com/settings/defaults`,
    "_blank",
  );
};
</script>

<template>
  <SettingsTab>
    <template #title>
      {{ $t("connection") }}
    </template>
    <template #description>
      {{ $t("connection_top", ["Kargo Entegratör"]) }}
    </template>

    <Plan v-if="accountDetails.plan" :account-details="accountDetails" />

    <div
      v-if="currentApiKey && !accountDetails.plan"
      class="flex flex-col justify-start gap-1"
    >
      <ApiError />
      <MdrFormField v-model="apiKey" :label="$t('api_key')" class="!w-1/2" />
      <button class="w-fit underline" @click="goToSaas">
        {{ $t("go_to_saas") }}
      </button>
      <div class="flex gap-2">
        <DangerButton class="max-w-fit" @click="deleteApiKey">
          {{ $t("disconnect") }}
        </DangerButton>
        <PrimaryButton class="max-w-fit" @click="updateKey">
          {{ $t("save") }}
        </PrimaryButton>
      </div>
    </div>

    <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 class="flex flex-col gap-3 mt-4">
      <template v-if="!accountDetails.plan && show">
        <MdrFormField v-model="apiKey" :label="$t('api_key')" class="!w-1/2" />
        <PrimaryButton class="max-w-fit" @click="updateKey">
          {{ $t("save") }}
        </PrimaryButton>
        <div>
          {{ $t("not-api-key") }}
          <a
            class="underline text-primary-600"
            href="https://app.kargoentegrator.com"
            target="_blank"
            >{{ $t("sign_up_now") }}</a
          >
        </div>
      </template>
      <div v-if="accountDetails.plan" class="flex flex-col gap-2">
        <MdrFormField
          v-model="currentApiKey"
          :label="$t('api_key')"
          class="!w-1/2"
          disabled
        />
        <span v-if="lastSyncTime"
          >{{ lastSyncTime }} {{ $t("equaled_on_that_date") }}</span
        >
        <button class="w-fit underline" @click="goToSaas">
          {{ $t("go_to_saas") }}
        </button>
        <div class="flex gap-2">
          <DangerButton class="max-w-fit" @click="deleteApiKey">
            {{ $t("disconnect") }}
          </DangerButton>
          <PrimaryButton @click="sync">
            {{ $t("sync_options") }}
          </PrimaryButton>
        </div>

        <span class="text-green-600 font-medium"
          >:white_check_mark: {{ $t("api_key_success") }}</span
        >
      </div>
    </div>
  </SettingsTab>
</template>
