<template>
  <q-scroll-area class="loyalty-suite-wrapper">
    <q-inner-loading :showing="loading">
      <q-spinner color="primary" size="70px" />
    </q-inner-loading>

    <template v-if="!loading">
      <div v-if="error" class="loyalty-suite-api-error-message">
        <q-icon name="error_outline" color="negative" size="md" />
        <span>{{ error }}</span>
      </div>

      <template v-else>
        <div class="loyalty-suite-settings">
          <div class="loyalty-suite-settings__title">
            <h1 class="loyalty-suite-settings__title-text">
              {{ $t('settingsEdit') }}
            </h1>
          </div>
          <q-form class="loyalty-suite-form" @validation-error="focusFirstTabWithError" @submit.prevent="submitForm">
            <div class="loyalty-suite-form__section loyalty-suite-form__section_tabs">
              <div class="loyalty-suite-form__section__tabs">
                <div class="loyalty-suite-form__section__tabs-wrapper">
                  <q-tabs v-model="activeTab" align="left">
                    <q-tab v-for="(section, index) in sections" :key="index" :name="section['value']"
                      :label="section['label']" />
                  </q-tabs>
                </div>
              </div>

              <div class="loyalty-suite-form__tab-panels">
                <div class="loyalty-suite-form__tab-panel" v-show="activeTab === 'main'" name="main">
                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.accountPage') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.accountPageHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-select v-model="settings.account_page_place" :options="accountPageOptions" map-options emit-value
                      outlined :rules="[val => val === 'woo' || val === 'custom' || $t('requiredField')]" />
                  </div>

                  <div v-if="settings.account_page_place === 'woo'"
                    class="loyalty-suite-form__row loyalty-suite-form__row_settings">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.accountPageName') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.accountPageNameHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-input v-model="settings.account_page_name" :rules="[val => !!val || $t('requiredField')]"
                      outlined />
                  </div>

                  <div v-if="settings.account_page_place === 'custom'"
                    class="loyalty-suite-form__row loyalty-suite-form__row_settings">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.chooseAccountPageCustom') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.accountPageCustomHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-select v-model="settings.account_page_custom" :options="accountCustomPageOptions" map-options
                      emit-value outlined :display-value="getCustomPageLabel"
                      :rules="[val => !!val || $t('requiredField')]" />
                  </div>

                  <div v-if="settings.account_page_place === 'custom'"
                    class="loyalty-suite-form__row loyalty-suite-form__row_settings">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.chooseAccountPageHideMode') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.accountPageHideModeHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-select v-model="settings.account_page_hide" :options="accountHideOptions" map-options emit-value
                      outlined :rules="[val => !!val || $t('requiredField')]" />
                  </div>

                  <div v-if="settings.account_page_hide === 'redirect' && settings.account_page_place === 'custom'"
                    class="loyalty-suite-form__row loyalty-suite-form__row_settings">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.chooseAccountPageRedirectUrl') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.accountPageRedirectUrlHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-input v-model="settings.account_page_redirect_url" :rules="[
                      val => !!val || $t('requiredField'),
                      val => isValidUrl(val) || $t('correctUrl')
                    ]" outlined />
                  </div>

                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.sharePage') }}
                      <q-icon
                        name="info_outline"
                        size="18px"
                        class="loyalty-suite-form__row-hint"
                      >
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.sharePageHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-select
                      v-model="settings.share_page_id"
                      :options="accountCustomPageOptions"
                      map-options
                      emit-value
                      outlined
                      :display-value="getSharePageLabel"
                      :rules="[val => !!val || $t('requiredField')]"
                    />
                  </div>

                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.showRanks') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.showRanksHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-toggle v-model="settings.show_ranks" />
                  </div>

                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.showAchievements') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.showAchievementsHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-toggle v-model="settings.show_achievements" />
                  </div>

                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.showRewards') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.showRewardsHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-toggle v-model="settings.show_rewards" />
                  </div>

                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.showChallenges') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.showChallengesHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-toggle v-model="settings.show_challenges" />
                  </div>
                </div>

                <div class="loyalty-suite-form__tab-panel" v-show="activeTab === 'currency'" name="currency">
                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.currency') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.currencyHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-select v-model="selectedCurrency" :options="currencyOptions" fill-input input-debounce="0"
                      :rules="[() => !!selectedCurrency || $t('requiredField')]" outlined>
                    </q-select>
                  </div>

                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.currencyPosition') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.currencyPositionHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-select v-model="selectedCurrencyPosition" :options="currencyPositionOptions" fill-input
                      input-debounce="0" :rules="[() => !!selectedCurrencyPosition || $t('requiredField')]" outlined>
                    </q-select>
                  </div>

                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.thousandSeparator') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.thousandSeparatorHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-input v-model="settings.thousand_separator" outlined />
                  </div>

                  <div class=" loyalty-suite-form__row loyalty-suite-form__row_settings">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.decimalSeparator') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.decimalSeparatorHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-input v-model="settings.decimal_separator" outlined />
                  </div>

                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.decimalNumber') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.decimalNumberHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-input v-model="settings.decimal_number" type="number"
                      :rules="[val => val !== null && val !== undefined && val !== '' || $t('requiredField')]"
                      outlined />
                  </div>
                </div>

                <div class="loyalty-suite-form__tab-panel" v-show="activeTab === 'colors'" name="colors">
                  <div v-for="(value, key) in settings.colors" :key="key"
                    class="loyalty-suite-form__row loyalty-suite-form__row_settings">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.color.' + key) }}
                    </span>
                    <q-input v-model="colorInputs[key]" @blur="handleColorBlur(key)" :lazy-rules="true"
                      spellcheck="false" :rules="[
                        val => !!val || $t('requiredField'),
                        val => /^rgba\(\s*\d{1,3},\s*\d{1,3},\s*\d{1,3},\s*(0|1|0?\.\d+)\s*\)$/.test(val)
                          || /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(val)
                          || $t('invalidColor')
                      ]" outlined>
                      <template v-slot:prepend>
                        <span class="loyalty-suite-form__color-preview" :style="{
                          background: settings.colors[key],
                        }"></span>
                      </template>
                      <template v-slot:append>
                        <q-icon name="colorize" class="cursor-pointer loyalty-suite-form__color-choose">
                          <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                            <q-color class="loyalty-suite-form__color" :model-value="settings.colors[key]"
                              @update:model-value="(val) => onColorChange(val, key)" format="rgba" no-header />
                          </q-popup-proxy>
                        </q-icon>
                        <q-icon v-if="colorInputs[key] !== DEFAULT_COLORS[key]" name="close"
                          class="cursor-pointer loyalty-suite-form__color-reset" @click.stop="resetColor(key)" />
                      </template>
                    </q-input>
                  </div>
                </div>

                <div class="loyalty-suite-form__tab-panel" v-show="activeTab === 'cards'" name="cards">
                  <div class="loyalty-suite-form__row loyalty-suite-form__row_full-width">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.achievementCardsStyle') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top right" self="top right">
                          {{ $t('settings.achievementCardsStyleHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <div class="loyalty-suite-form__cards">
                      <div v-for="(cardStyle, index) in cardStyles" :key="index" class="loyalty-suite-form__card">
                        <div class="loyalty-suite-form__card-wrapper"
                          @click="settings.achievement_style = cardStyle.value">
                          <img :src="cardStyle.images.achievement" alt="" class="loyalty-suite-form__card-img">
                          <q-radio v-model="settings.achievement_style" :val="cardStyle.value" :label="cardStyle.label"
                            dense />
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="loyalty-suite-form__row loyalty-suite-form__row_full-width">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.rankCardsStyle') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top right" self="top right">
                          {{ $t('settings.rankCardsStyleHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <div class="loyalty-suite-form__cards">
                      <div v-for="(cardStyle, index) in cardStyles" :key="index" class="loyalty-suite-form__card">
                        <div class="loyalty-suite-form__card-wrapper" @click="settings.rank_style = cardStyle.value">
                          <img :src="cardStyle.images.rank" alt="" class="loyalty-suite-form__card-img">
                          <q-radio v-model="settings.rank_style" :val="cardStyle.value" :label="cardStyle.label"
                            dense />
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="loyalty-suite-form__row loyalty-suite-form__row_full-width">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.challengeCardsStyle') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top right" self="top right">
                          {{ $t('settings.challengeCardsStyleHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <div class="loyalty-suite-form__cards">
                      <div v-for="(cardStyle, index) in cardStyles" :key="index" class="loyalty-suite-form__card">
                        <div class="loyalty-suite-form__card-wrapper"
                          @click="settings.challenge_style = cardStyle.value">
                          <img :src="cardStyle.images.challenge" alt="" class="loyalty-suite-form__card-img">
                          <q-radio v-model="settings.challenge_style" :val="cardStyle.value" :label="cardStyle.label"
                            dense />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div class="loyalty-suite-form__tab-panel" v-show="activeTab === 'notifications'" name="notifications">
                  <div class="loyalty-suite-form__row loyalty-suite-form__row_columns">
                    <div class="loyalty-suite-form__column">
                      {{ $t('popup') }}
                    </div>
                    <div class="loyalty-suite-form__column">
                      {{ $t('email') }}
                    </div>
                  </div>
                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings loyalty-suite-form__row_toggles">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.notificationNewRankSet') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.notificationNewRankSetHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-toggle v-model="settings.notification_new_rank_set" />
                    <q-toggle v-model="settings.email_new_rank_set" />
                  </div>

                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings loyalty-suite-form__row_toggles">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.notificationRank') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.notificationRankHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-toggle v-model="settings.notification_complete_rank" />
                    <q-toggle v-model="settings.email_complete_rank" />
                  </div>

                  <span class="loyalty-suite-form__row-divider"></span>

                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings loyalty-suite-form__row_toggles">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.notificationNewAchievement') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.notificationNewAchievementHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-toggle v-model="settings.notification_new_achievement" />
                    <q-toggle v-model="settings.email_new_achievement" />
                  </div>

                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings loyalty-suite-form__row_toggles">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.notificationAchievement') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.notificationAchievementHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-toggle v-model="settings.notification_complete_achievement" />
                    <q-toggle v-model="settings.email_complete_achievement" />
                  </div>

                  <span class="loyalty-suite-form__row-divider"></span>

                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings loyalty-suite-form__row_toggles">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.notificationNewChallenge') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.notificationNewChallengeHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-toggle v-model="settings.notification_new_challenge" />
                    <q-toggle v-model="settings.email_new_challenge" />
                  </div>

                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings loyalty-suite-form__row_toggles">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.notificationChallenge') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.notificationChallengeHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-toggle v-model="settings.notification_complete_challenge" />
                    <q-toggle v-model="settings.email_complete_challenge" />
                  </div>

                  <span v-if="isPro" class="loyalty-suite-form__row-divider"></span>

                  <div v-if="isPro" class="loyalty-suite-form__row loyalty-suite-form__row_settings loyalty-suite-form__row_toggles">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.notificationNewSubmission') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.notificationNewSubmissionHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-toggle v-model="settings.notification_new_submission" />
                  </div>

                  <div v-if="isPro" class="loyalty-suite-form__row loyalty-suite-form__row_settings loyalty-suite-form__row_toggles">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.notificationSubmissionCompleted') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.notificationSubmissionCompletedHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-toggle v-model="settings.notification_submission_completed" />
                    <q-toggle v-model="settings.email_submission_completed" />
                  </div>

                  <div v-if="isPro" class="loyalty-suite-form__row loyalty-suite-form__row_settings loyalty-suite-form__row_toggles">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.notificationSubmissionRejected') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.notificationSubmissionRejectedHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-toggle v-model="settings.notification_submission_rejected" />
                    <q-toggle v-model="settings.email_submission_rejected" />
                  </div>

                  <span class="loyalty-suite-form__row-divider"></span>

                  <div class="loyalty-suite-form__row loyalty-suite-form__row_settings loyalty-suite-form__row_toggles">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.notificationWalletLimit') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.notificationWalletLimitHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-toggle v-model="settings.notification_wallet_limit" />
                    <q-toggle v-model="settings.email_wallet_limit" />
                  </div>

                  <div v-if="isPro" class="loyalty-suite-form__row loyalty-suite-form__row_settings loyalty-suite-form__row_toggles">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('settings.notificationWalletCashback') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top middle" self="top middle">
                          {{ $t('settings.notificationWalletCashbackHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-toggle v-model="settings.notification_wallet_cashback" />
                    <q-toggle v-model="settings.email_wallet_cashback" />
                  </div>
                </div>
              </div>
            </div>

            <div class="loyalty-suite-form__action">
              <q-btn type="submit" :label="$t('save')" :loading="changeLoading" color="primary" />
            </div>

            <div v-if="addError" class="loyalty-suite-form__action-error">
              {{ $t(addError) }}
            </div>

            <div v-if="addSuccess" class="loyalty-suite-form__action-success">
              {{ $t(addSuccess) }}
            </div>

            <q-dialog v-model="confirmLeave">
              <q-card>
                <q-card-section>
                  <span>{{ $t('unsavedChanges') }}</span>
                </q-card-section>
                <q-card-actions align="center">
                  <q-btn :label="$t('cancel')" color="negative" v-close-popup @click="cancelDiscardChanges" />
                  <q-btn :label="$t('discardChanges')" color="primary" v-close-popup @click="confirmDiscardChanges" />
                </q-card-actions>
              </q-card>
            </q-dialog>
          </q-form>
        </div>
      </template>
    </template>
  </q-scroll-area>
</template>

<script lang="ts">
import { defineComponent, ref, onBeforeMount, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';

export default defineComponent({
  setup() {
    const router = useRouter();
    const { t } = useI18n();
    const loading = ref(true);
    const changeLoading = ref(false);
    const originalSettings = ref<string | null>(null);
    const pendingRoute = ref<null | { path: string; query: Record<string, any> }>(null);
    const confirmLeave = ref(false);
    const isDirty = ref(false);
    const error = ref<string | null>(null);
    const addError = ref<string | null>(null);
    const addSuccess = ref<string | null>(null);
    const apiRoutes = window.loyalty_suite_admin_data.apiRoutes;
    const homeUrl = window.loyalty_suite_admin_data.homeUrl;
    const cardsImages = window.loyalty_suite_admin_data.cardsImages;
    const isWooEnabled = window.loyalty_suite_admin_data.isWooEnabled;
    const nonce = window.loyalty_suite_admin_data.nonce;
    const isPro = window.loyalty_suite_admin_data.isPro;
    const accountCustomPageOptions = ref([]);
    const accountPageOptions = [
      { label: t('settings.accountPageCustom'), value: 'custom' }
    ];
    const activeTab = ref('main');
    const sections = [
      { label: t('main'), value: 'main' },
      { label: t('settings.currencySettings'), value: 'currency' },
      { label: t('settings.colorSettings'), value: 'colors' },
      { label: t('settings.cardsSettings'), value: 'cards' },
      { label: t('settings.notificationSettings'), value: 'notifications' },
    ];

    const focusFirstTabWithError = () => {
      const errorField = document.querySelector('.q-field--error');
      if (!errorField) return;

      const tabPanel = errorField.closest('.loyalty-suite-form__tab-panel');
      if (!tabPanel) return;

      const tabName = tabPanel.getAttribute('name');
      if (tabName && sections.find(s => s.value === tabName)) {
        activeTab.value = tabName;
      }
    };

    if (isWooEnabled) {
      accountPageOptions.push({
        label: t('settings.accountPageWoo'), value: 'woo',
      })
    }

    const accountHideOptions = [
      { label: t('settings.accountPageHideMenu'), value: 'menu' },
      { label: t('settings.accountPageRedirect'), value: 'redirect' },
      { label: t('settings.accountPageVisible'), value: 'visible' }
    ];

    const cardStyles = [
      {
        label: t('settings.classic'),
        value: 'classic',
        images: {
          achievement: cardsImages['classic_achievement'],
          challenge: cardsImages['classic_challenge'],
          rank: cardsImages['classic_rank'],
        }
      },
      {
        label: t('settings.modern'),
        value: 'modern',
        images: {
          achievement: cardsImages['modern_achievement'],
          challenge: cardsImages['modern_challenge'],
          rank: cardsImages['modern_rank'],
        }
      }
    ];

    const DEFAULT_COLORS = {
      'primary': 'rgba(99,102,241,1)',
      'positive': 'rgba(33,186,69,1)',
      'negative': 'rgba(226,2,28,1)',
      'dark': 'rgba(51,65,85,1)',
      'light': 'rgba(255,255,255,1)',
      'borders': 'rgba(176,182,188,1)',
    } as const;

    type ColorKeys = keyof typeof DEFAULT_COLORS;

    const colorInputs = ref<Record<ColorKeys, string>>({});

    const isValidHex = (hex: string): boolean => {
      return /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(hex);
    };

    const onColorChange = (val: string, key: ColorKeys) => {
      if (val.startsWith('#')) {
        if (isValidHex(val)) {
          const rgba = hexToRgba(val);
          settings.value.colors[key] = rgba;
          colorInputs.value[key] = rgba;
        } else {
          colorInputs.value[key] = val;
        }
      } else {
        settings.value.colors[key] = val;
        colorInputs.value[key] = val;
      }
    };

    const handleColorBlur = (key: ColorKeys) => {
      const val = colorInputs.value[key];

      if (val.startsWith('#')) {
        if (isValidHex(val)) {
          const rgba = hexToRgba(val);
          settings.value.colors[key] = rgba;
          colorInputs.value[key] = rgba;
        }
      } else if (/^rgba\(\s*\d{1,3},\s*\d{1,3},\s*\d{1,3},\s*(0|1|0?\.\d+)\s*\)$/.test(val)) {
        settings.value.colors[key] = val;
      }
    };

    const hexToRgba = (hex: string): string => {
      hex = hex.replace('#', '');
      let r = 0, g = 0, b = 0, a = 1;

      if (hex.length === 3) {
        r = parseInt(hex[0] + hex[0], 16);
        g = parseInt(hex[1] + hex[1], 16);
        b = parseInt(hex[2] + hex[2], 16);
      } else if (hex.length === 6) {
        r = parseInt(hex.slice(0, 2), 16);
        g = parseInt(hex.slice(2, 4), 16);
        b = parseInt(hex.slice(4, 6), 16);
      } else if (hex.length === 8) {
        r = parseInt(hex.slice(0, 2), 16);
        g = parseInt(hex.slice(2, 4), 16);
        b = parseInt(hex.slice(4, 6), 16);
        a = +(parseInt(hex.slice(6, 8), 16) / 255).toFixed(3);
      } else {
        throw new Error('Invalid HEX color');
      }

      return `rgba(${r},${g},${b},${a})`;
    };

    const resetColor = (key: ColorKeys) => {
      settings.value.colors[key] = DEFAULT_COLORS[key];
      colorInputs.value[key] = DEFAULT_COLORS[key];
    };

    const settings = ref<{
      currency: string,
      currency_position: string,
      thousand_separator: string,
      decimal_separator: string,
      decimal_number: number,
      account_page_place: string,
      account_page_name: string,
      account_page_custom: number | null,
      share_page_id: number | null,
      account_page_hide: string,
      account_page_redirect_url: string,
      show_ranks: boolean,
      show_achievements: boolean,
      show_challenges: boolean,
      show_rewards: boolean,
      notification_complete_challenge: boolean,
      notification_new_challenge: boolean,
      notification_new_rank_set: boolean,
      notification_complete_rank: boolean,
      notification_complete_achievement: boolean,
      notification_new_achievement: boolean,
      notification_wallet_limit: boolean,
      notification_wallet_cashback: boolean,
      notification_new_submission: boolean,
      notification_submission_completed: boolean,
      notification_submission_rejected: boolean,
      email_complete_challenge: boolean,
      email_new_challenge: boolean,
      email_new_rank_set: boolean,
      email_complete_rank: boolean,
      email_complete_achievement: boolean,
      email_new_achievement: boolean,
      email_wallet_limit: boolean,
      email_wallet_cashback: boolean,
      email_submission_completed: boolean,
      email_submission_rejected: boolean,
      colors: Record<ColorKeys, string>,
      achievement_style: string,
      challenge_style: string,
      rank_style: string,
    }>({
      currency: '$',
      currency_position: 'left',
      thousand_separator: ',',
      decimal_separator: '.',
      decimal_number: 2,
      account_page_place: isWooEnabled ? 'woo' : 'custom',
      account_page_name: '',
      account_page_custom: null,
      share_page_id: null,
      account_page_hide: 'menu',
      account_page_redirect_url: homeUrl,
      show_ranks: true,
      show_achievements: true,
      show_challenges: true,
      show_rewards: true,
      notification_complete_challenge: true,
      notification_new_challenge: false,
      notification_new_rank_set: false,
      notification_complete_rank: true,
      notification_complete_achievement: true,
      notification_new_achievement: false,
      notification_wallet_limit: true,
      notification_wallet_cashback: true,
      notification_new_submission: true,
      notification_submission_completed: true,
      notification_submission_rejected: true,
      email_complete_challenge: true,
      email_new_challenge: false,
      email_new_rank_set: false,
      email_complete_rank: true,
      email_complete_achievement: true,
      email_new_achievement: false,
      email_wallet_limit: true,
      email_wallet_cashback: true,
      email_submission_completed: true,
      email_submission_rejected: true,
      colors: { ...DEFAULT_COLORS },
      achievement_style: 'classic',
      challenge_style: 'classic',
      rank_style: 'classic',
    });

    const isValidUrl = (val: string): boolean => {
      try {
        new URL(val);
        return true;
      } catch {
        return false;
      }
    };

    const currencyOptions = ref([
      { value: 'USD', label: t('USD') },
      { value: 'EUR', label: t('EUR') },
      { value: 'GBP', label: t('GBP') },
      { value: 'CHF', label: t('CHF') },
      { value: 'SEK', label: t('SEK') },
      { value: 'NOK', label: t('NOK') },
      { value: 'DKK', label: t('DKK') },
      { value: 'PLN', label: t('PLN') },
      { value: 'CZK', label: t('CZK') },
      { value: 'HUF', label: t('HUF') },
      { value: 'RON', label: t('RON') },
      { value: 'BGN', label: t('BGN') },
      { value: 'UAH', label: t('UAH') },
      { value: 'BYN', label: t('BYN') },
      { value: 'MDL', label: t('MDL') },
      { value: 'RSD', label: t('RSD') },
      { value: 'BAM', label: t('BAM') },
      { value: 'ALL', label: t('ALL') },
      { value: 'HRK', label: t('HRK') },
      { value: 'GEL', label: t('GEL') },
      { value: 'JPY', label: t('JPY') },
      { value: 'KRW', label: t('KRW') },
      { value: 'HKD', label: t('HKD') },
      { value: 'SGD', label: t('SGD') },
      { value: 'TWD', label: t('TWD') },
      { value: 'ILS', label: t('ILS') },
      { value: 'AUD', label: t('AUD') },
      { value: 'NZD', label: t('NZD') },
      { value: 'CAD', label: t('CAD') },
      { value: 'MXN', label: t('MXN') },
      { value: 'ARS', label: t('ARS') },
      { value: 'AED', label: t('AED') },
      { value: 'BRL', label: t('BRL') },
      { value: 'CLP', label: t('CLP') },
      { value: 'UYU', label: t('UYU') },
      { value: 'RUB', label: t('RUB') },
      { value: 'CNY', label: t('CNY') },
      { value: 'INR', label: t('INR') },
      { value: 'PKR', label: t('PKR') },
      { value: 'UZS', label: t('UZS') },
      { value: 'KZT', label: t('KZT') },
      { value: 'KGS', label: t('KGS') }
    ]);

    const currencyPositionOptions = ref([
      { value: 'left', label: t('left') },
      { value: 'right', label: t('right') },
      { value: 'leftspace', label: t('leftWithSpace') },
      { value: 'rightspace', label: t('rightWithSpace') }
    ]);

    const selectedCurrency = computed({
      get: () => {
        return (
          currencyOptions.value.find(option => option.value === settings.value.currency) ||
          currencyOptions.value[0]
        );
      },
      set: (newValue) => {
        settings.value.currency = newValue?.value || '$';
      }
    });

    const selectedCurrencyPosition = computed({
      get: () => {
        return (
          currencyPositionOptions.value.find(option => option.value === settings.value.currency_position) ||
          currencyPositionOptions.value[0]
        );
      },
      set: (newValue) => {
        settings.value.currency_position = newValue?.value || 'left';
      }
    });

    const getCustomPageLabel = computed(() => {
      const selected = accountCustomPageOptions.value.find(
        option => option.value === settings.value.account_page_custom
      );
      return selected ? selected.label : '';
    });

    const getSharePageLabel = computed(() => {
      const selected = accountCustomPageOptions.value.find(
        option => option.value === settings.value.share_page_id
      );
      return selected ? selected.label : '';
    });

    const handleNavigation = (to: { path: string; query: Record<string, any> }) => {
      if (isDirty.value) {
        confirmLeave.value = true;
        pendingRoute.value = to;
        return false;
      }
      return true;
    };

    const confirmDiscardChanges = () => {
      if (pendingRoute.value) {
        router.push(pendingRoute.value);
      }
      isDirty.value = false;
      confirmLeave.value = false;
    };

    const cancelDiscardChanges = () => {
      confirmLeave.value = false;
      pendingRoute.value = null;
    };

    router.beforeEach((to, from, next) => {
      if (handleNavigation(to)) {
        next();
      }
    });

    const fetchSettings = async () => {
      try {
        const response = await fetch(apiRoutes.admin.settings, {
          method: 'GET',
          headers: {
            'X-WP-Nonce': nonce,
            'Content-Type': 'application/json',
          }
        });

        const data = await response.json().catch(() => null);

        if (!response.ok) {
          addError.value = data?.error;
          return;
        }

        settings.value = {
          ...data,
        };

        Object.keys(settings.value.colors).forEach((key) => {
          const colorKey = key as ColorKeys;
          colorInputs.value[colorKey] = settings.value.colors[colorKey];
        });

        accountCustomPageOptions.value = Array.isArray(data.pages) ? data.pages : [];
      } catch (err) {
        error.value = err instanceof Error ? err.message : t('couldNotFetchData');
        console.error('API Error:', error.value);
      }
    };

    const submitForm = async () => {
      try {
        changeLoading.value = true;
        const formData = new FormData();

        formData.append('currency', String(settings.value.currency));
        formData.append('currency_position', String(settings.value.currency_position));
        formData.append('thousand_separator', String(settings.value.thousand_separator));
        formData.append('thousand_separator', String(settings.value.thousand_separator));
        formData.append('decimal_separator', String(settings.value.decimal_separator));
        formData.append('decimal_number', String(settings.value.decimal_number));
        formData.append('account_page_place', String(settings.value.account_page_place));
        formData.append('account_page_name', String(settings.value.account_page_name));
        formData.append('account_page_custom', String(settings.value.account_page_custom));
        formData.append('share_page_id', String(settings.value.share_page_id));
        formData.append('account_page_hide', String(settings.value.account_page_hide));
        formData.append('account_page_redirect_url', String(settings.value.account_page_redirect_url));
        formData.append('show_ranks', String(settings.value.show_ranks));
        formData.append('show_achievements', String(settings.value.show_achievements));
        formData.append('show_challenges', String(settings.value.show_challenges));
        formData.append('show_rewards', String(settings.value.show_rewards));
        formData.append('notification_complete_challenge', String(settings.value.notification_complete_challenge));
        formData.append('notification_new_challenge', String(settings.value.notification_new_challenge));
        formData.append('notification_new_rank_set', String(settings.value.notification_new_rank_set));
        formData.append('notification_complete_rank', String(settings.value.notification_complete_rank));
        formData.append('notification_complete_achievement', String(settings.value.notification_complete_achievement));
        formData.append('notification_new_achievement', String(settings.value.notification_new_achievement));
        formData.append('notification_wallet_limit', String(settings.value.notification_wallet_limit));
        formData.append('notification_wallet_cashback', String(settings.value.notification_wallet_cashback));
        formData.append('notification_new_submission', String(settings.value.notification_new_submission));
        formData.append('notification_submission_completed', String(settings.value.notification_submission_completed));
        formData.append('notification_submission_rejected', String(settings.value.notification_submission_rejected));
        formData.append('email_complete_challenge', String(settings.value.email_complete_challenge));
        formData.append('email_new_challenge', String(settings.value.email_new_challenge));
        formData.append('email_new_rank_set', String(settings.value.email_new_rank_set));
        formData.append('email_complete_rank', String(settings.value.email_complete_rank));
        formData.append('email_complete_achievement', String(settings.value.email_complete_achievement));
        formData.append('email_new_achievement', String(settings.value.email_new_achievement));
        formData.append('email_wallet_limit', String(settings.value.email_wallet_limit));
        formData.append('email_wallet_cashback', String(settings.value.email_wallet_cashback));
        formData.append('email_submission_completed', String(settings.value.email_submission_completed));
        formData.append('email_submission_rejected', String(settings.value.email_submission_rejected));
        formData.append('colors', JSON.stringify(settings.value.colors));
        formData.append('achievement_style', String(settings.value.achievement_style));
        formData.append('challenge_style', String(settings.value.challenge_style));
        formData.append('rank_style', String(settings.value.rank_style));

        const response = await fetch(apiRoutes.admin.settings_save, {
          method: 'POST',
          headers: {
            'X-WP-Nonce': nonce
          },
          body: formData
        });

        const responseData = await response.json().catch(() => null);

        if (!response.ok) {
          addError.value = responseData?.error;
          return;
        }

        addSuccess.value = 'saved';
        isDirty.value = false;
      } catch (err) {
        error.value = err instanceof Error ? err.message : 'Error submitting data';
      } finally {
        changeLoading.value = false;
      }
    };

    onBeforeMount(async () => {
      await fetchSettings();

      loading.value = false;
      originalSettings.value = JSON.stringify(settings.value);

      watch(settings, () => {
        isDirty.value = JSON.stringify(settings.value) !== originalSettings.value;
        addSuccess.value = null;
      }, { deep: true });
    });

    return {
      changeLoading,
      loading,
      error,
      addError,
      addSuccess,
      confirmLeave,
      settings,
      selectedCurrency,
      currencyPositionOptions,
      selectedCurrencyPosition,
      currencyOptions,
      submitForm,
      confirmDiscardChanges,
      cancelDiscardChanges,
      accountPageOptions,
      accountCustomPageOptions,
      getCustomPageLabel,
      getSharePageLabel,
      resetColor,
      DEFAULT_COLORS,
      accountHideOptions,
      isValidUrl,
      handleColorBlur,
      colorInputs,
      onColorChange,
      activeTab,
      sections,
      focusFirstTabWithError,
      cardStyles,
      isPro
    };
  }
});
</script>

<style lang="scss" scoped>
.loyalty-suite-settings {
  display: flex;
  flex-direction: column;
  width: 100%;

  &__title {
    display: flex;
    align-items: center;
    width: 100%;
    margin-bottom: 25px;

    &-text {
      display: flex;
      font-size: 22px;
    }
  }

  .loyalty-suite-form {
    width: 700px;
  }
}
</style>
