<template>
  <div class="wcc-loader-view" style="min-height: 400px" v-if="!isLoaded">
    <p class="wcc-loading-text">
      <loader />
      {{ $i18n.__("Loading...", "webtoffee-cookie-consent") }}
    </p>
  </div>
  <div
    class="wcc-section wcc-license-section wcc-zero--padding wcc-zero--margin"
    v-else
  >
    <div class="wcc-license-section-content">
      <div class="wcc-section-content">
        <div class="wcc-row wcc-banner-selector-section">
          <div class="wcc-col-8 wcc-align-center wcc-section-header-title">
            {{
              $i18n.__("License activation", "webtoffee-cookie-consent")
            }}
          </div>
        </div>
        <div class="wcc-license-details-wrap">
          <div class="wcc-license-email-wrap">
            <label
              for="wcc-license-email"
              class="wcc-license-email-title wcc-title-label"
              id="wcc-license-email-title"
            >
              {{ $i18n.__("Email id", "webtoffee-cookie-consent") }}
            </label>
            <input
              type="text"
              class="wcc-license-email wcc-input-text"
              id="wcc-license-email"
              placeholder="abc@gmail.com"
              :disabled="licenseActive"
              v-model="email"
              :data-test-id="`wcc-license-email-input`"
            />
          </div>
          <div class="wcc-license-key-wrap">
            <label
              for="wcc-license-key"
              class="wcc-license-key-title wcc-title-label"
              id="wcc-license-key-title"
            >
              {{ $i18n.__("API license key", "webtoffee-cookie-consent") }}
            </label>
            <input
              type="text"
              class="wcc-license-key wcc-input-text"
              id="wcc-license-key"
              :disabled="licenseActive"
              :value="maskedLicenseKey"
              @input="updateLicenseKey($event.target.value)"
              :data-test-id="`wcc-license-key-input`"
            />
            <p class="wcc-help-license-key-title" id="wcc-license-key-help">
              Check
              <a
                href="https://www.webtoffee.com/my-account/my-api-keys/"
                target="_blank"
                >My Account</a
              >
              for API Keys and API Downloads.
            </p>
          </div>
          <div class="wcc-activate-btn-wrap" v-if="!licenseActive">
            <base-button
              class="wcc-button wcc-button-blue wcc-activate-btn"
              @click.native="activate(licenseKey, email)"
              style=""
              :disabled="disabled"
              :data-test-id="`wcc-license-activate-button`"
            >
              {{ $i18n.__("Activate", "webtoffee-cookie-consent") }}
            </base-button>
          </div>
          <div class="wcc-deactivate-btn-wrap" v-else>
            <base-button
              class=" wcc-button-red wcc-deactivate-btn"
              @click.native="deactivate"
              style=""
              :disabled="disabled"
              :data-test-id="`wcc-license-deactivate-button`"
            >
              {{ $i18n.__("Deactivate", "webtoffee-cookie-consent") }}
            </base-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Loader from "@/components/elements/Loader.vue";
import wccRest from "@/helpers/api";

export default {
  name: "Customize",
  components: {
    Loader,
  },
  data() {
    return {
      loading: true,
      licenseActive: false,
      licenseKey: "",
      email: "",
      disabled: false
    };
  },
  methods: {
    updateLicenseKey(value) {
      this.licenseKey = value;
    },
    async activate(licenseKey, email) {
      if("" === email || "" === licenseKey) {
        this.$root.$emit("triggerNotification", {
          type: "error",
          message: this.$i18n.__(
            "Please enter a valid email and license key",
            "webtoffee-cookie-consent"
          ),
        });
        return;
      }
      try {
        this.disabled = true; // Set loading state to true

        const response = await wccRest.post({
          path: "license/activate",
          data: { key: licenseKey, email: email },
        });

        if (response !== null) {
          let status = response.success;
          let message = response.data;
          if (status) {
            this.licenseActive = true;
            this.$root.$emit("triggerNotification", {
              type: "success",
              message: this.$i18n.__(
                "License activated successfully!",
                "webtoffee-cookie-consent"
              ),
            });
            let data = {};
            data.status = "active";
            this.setOption("license", data);
            this.saveOptions();
          } else {
            this.showErrors(message);
          }
        }
      } catch (error) {
        console.error(error);
      } finally {
        this.disabled = false; // Set loading state to false after action completes
      }
    },
    async deactivate() {
      try {
        this.disabled = true; // Set loading state to true

        const response = await wccRest.post({
          path: "license/deactivate",          
        });

        if (response !== null) {
          let status = response.success;
          let message = response.data;
          if (status) {
            this.licenseActive = false;
            this.$root.$emit("triggerNotification", {
              type: "success",
              message: this.$i18n.__(
                "License deactivated successfully!",
                "webtoffee-cookie-consent"
              ),
            });
            let data = {};
            data.status = "";
            this.setOption("license", data);
            this.saveOptions();
          } else {
            this.showErrors(message);
          }
        }
      } catch (error) {
        console.error(error);
      } finally {
        this.disabled = false; // Set loading state to false after action completes
      }
    },
    showErrors(message) {
      this.$root.$emit("triggerNotification", {
        type: "error",
        message: message,
      });
    },
  },
  computed: {
    isLoaded() {
      return !this.loading;
    },
    maskedLicenseKey() {
      if (this.licenseActive) {
        if (!this.licenseKey || this.licenseKey.length < 8) return this.licenseKey;
        const maskedMiddle = '*'.repeat(this.licenseKey.length - 8);
        return this.licenseKey.substring(0, 4) + maskedMiddle + this.licenseKey.substring(this.licenseKey.length - 4);
      } else {
        return this.licenseKey;
      }
    },
  },
  watch: {},
  async created() {
    try {
      const licenseData = await wccRest.get({
        path: "license",
      });
      const { status, licence_key, licence_email } = licenseData;
      this.licenseActive = status !== '' ? status : false;
      this.licenseKey = licence_key;
      this.email = licence_email;
    } catch (error) {
      console.error("API Error:", error);
    } finally {
      this.loading = false; // Set loading state to false after component is created
    }
  },
};
</script>
  <style lang="scss">
@include wrap-class() {
  .wcc-license-section-content {
    border: 1px solid #eaebed;
    border-radius: 12px;
    margin: 8px 15px 0px 15px;
    &.wcc-nav-tab-content-container {
      padding: 0px 20px 15px 33px;
      border-bottom-right-radius: 16px;
    }
    max-width: 1097px;
    width:auto;
  }

  .wcc-license-details-wrap {
    padding: 0px 0px 20px 15px;
  }
  .wcc-section-header-title {
    color: #2a3646;
    font-size: 16px;
    font-style: normal;
    font-weight: 600;
    line-height: 28px;
  }
  .wcc-license-details-wrap > div {
    margin-bottom: 15px;
  }
  .wcc-title-label {
    color: #2a3646;
    font-size: 14px;
    font-style: normal;
    font-weight: 500;
    line-height: 16px;
    min-width: 120px;
  }
  .wcc-activate-btn-wrap .wcc-button-blue {
    background-color: #3157a6;
    border-radius: 4px;
  }
  .wcc-deactivate-btn-wrap .wcc-button-red,
  .wcc-deactivate-btn-wrap .wcc-button-red:hover {
    background-color: #ffeded;
    color: #d63638;
    border-radius: 4px;
    border-style: none;
	width: auto;
    min-width: 80px;
    padding: 8px 14px;
    font-weight: 500;
    font-size: 14px;
    cursor: pointer;
    line-height: 16px;
  }

  .wcc-input-text {
    border-radius: 6px;
    border: 1.5px solid var(--neutral-colours-neutral-100, #bdc1c6);
    background: #fff;
    width: 240px;
  }
  .wcc-input-text:disabled {
	opacity: 0.5;
	background: #EFEFF1;
  }
  .wcc-help-license-key-title {
    margin: 5px 0px 0px 120px;
    font-size: 12px;
  }
}
</style>