<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-rank">
          <div class="loyalty-suite-rank__title">
            <q-btn icon="arrow_back" color="primary" class="loyalty-suite-form__back" @click="goBack" />
            <h1 class="loyalty-suite-rank__title-text">
              {{ isEditing ? $t('rankSetEdit') : $t('rankSetAdd') }}
            </h1>
          </div>

          <q-form class="loyalty-suite-form" @submit.prevent="submitForm">
            <div class="loyalty-suite-form__section">
              <div class="loyalty-suite-form__title">{{ $t('setSettings') }}</div>

              <div class="loyalty-suite-form__row">
                <span class="loyalty-suite-form__row-label">
                  {{ $t('name') }}
                  <span class="loyalty-suite-form__row-label-required">*</span>
                  <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                    <q-tooltip anchor="top right" self="top right">
                      {{ $t('rankSetNameHint') }}
                    </q-tooltip>
                  </q-icon>
                </span>
                <q-input v-model="rankSet.name" outlined required
                  :rules="[val => val && val.length > 0 || $t('requiredField')]" />
              </div>

              <div class="loyalty-suite-form__row">
                <span class="loyalty-suite-form__row-label">
                  {{ $t('rankSetOrder') }}
                  <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                    <q-tooltip anchor="top right" self="top right">
                      {{ $t('rankSetOrderHint') }}
                    </q-tooltip>
                  </q-icon>
                </span>
                <q-select v-model="rankSet.order" :options="rankSetOrderOptions" emit-value map-options
                  fill-input input-debounce="0" outlined>
                  <template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-grey">{{ $t('noResultsFound') }}</q-item-section>
                    </q-item>
                  </template>

                  <template v-slot:option="scope">
                    <q-item v-bind="scope.itemProps">
                      <q-item-section>
                        <q-item-label>{{ scope.opt.label }}</q-item-label>
                      </q-item-section>
                      <q-item-section side>
                        <q-icon name="info_outline" class="loyalty-suite-form__select-info" size="18px">
                          <q-tooltip anchor="top right" self="top right">
                            {{ $t(`opt_rankSet_${scope.opt.value}`) }}
                          </q-tooltip>
                        </q-icon>
                      </q-item-section>
                    </q-item>
                  </template>
                </q-select>
              </div>

              <div class="loyalty-suite-form__row loyalty-suite-form__row_full-width">
                <span class="loyalty-suite-form__row-label">
                  {{ $t('description') }}
                  <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                    <q-tooltip anchor="top right" self="top right">
                      {{ $t('rankSetDescriptionHint') }}
                    </q-tooltip>
                  </q-icon>
                </span>
                <Editor v-model="rankSet.description" />
              </div>

              <div class="loyalty-suite-form__row loyalty-suite-form__row_toggler">
                <q-toggle v-model="rankSet.show" :label="rankSet.show ? $t('showRankSet') : $t('hideRankSet')" />
              </div>
              <div class="loyalty-suite-form__row loyalty-suite-form__row_toggler">
                <q-toggle v-model="rankSet.active" :label="rankSet.active ? $t('enabledRankSet') : $t('disabledRankSet')"
                  @update:model-value="confirmDeactivation" />
              </div>
            </div>

            <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="(rank, index) in rankSet.ranks" :key="index" :name="index"
                      :label="`${$t('rank')} #${index + 1}`" />
                  </q-tabs>
                </div>
                <div class="loyalty-suite-form__section__tabs-button">
                  <q-btn color="primary" icon="add" @click="addRank" />
                </div>
              </div>

              <q-tab-panels v-model="activeTab">
                <q-tab-panel v-for="(rank, index) in rankSet.ranks" :key="index" :name="index">
                  <div class="loyalty-suite-form__title">{{ $t('mainSettings') }}</div>
                  <div class="loyalty-suite-form__row">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('name') }}
                      <span class="loyalty-suite-form__row-label-required">*</span>
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top right" self="top right">
                          {{ $t('rankNameHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-input v-model="rank.name" outlined required
                      :rules="[val => val && val.length > 0 || $t('requiredField')]" />
                  </div>

                  <div class="loyalty-suite-form__row">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('imageType') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top right" self="top right">
                          {{ $t('imageTypeHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-select :model-value="getSelectedImageType(index).value"
                      @update:model-value="val => getSelectedImageType(index).value = val" :options="imageTypeOptions"
                      fill-input input-debounce="0"
                      :rules="[() => !!getSelectedImageType(index).value || $t('requiredField')]" outlined />
                  </div>

                  <div v-if="rank.image_type === 'icon'" class="loyalty-suite-form__row">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('icon') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top right" self="top right">
                          {{ $t('iconHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <div class="loyalty-suite-form__preview"
                      :class="{ 'loyalty-suite-form__preview_empty': !rank.icon }" @click="openLibrary(index)">
                      <div class="loyalty-suite-form__preview-container">
                        <img v-if="rank.previewUrl" :src="rank.previewUrl" class="loyalty-suite-form__preview-img" />
                        <q-btn v-if="rank.icon" icon="close" color="negative" @click.stop="removeIcon(index)"
                          class="loyalty-suite-form__preview-remove" />
                        <q-icon v-else name="file_upload" class="loyalty-suite-form__preview-icon" />
                        <span v-if="rank.previewName" class="loyalty-suite-form__preview-name">
                          {{ rank.previewName }}
                        </span>
                        <span v-else class="loyalty-suite-form__preview-label">
                          {{ $t('fileUpload') }}
                        </span>
                      </div>
                    </div>
                  </div>

                  <div v-if="rank.image_type === 'image'" class="loyalty-suite-form__row">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('image') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top right" self="top right">
                          {{ $t('imageHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <WpMediaUploader v-model="rank.image" @update:modelValue="id => setImage(id, index)" />
                  </div>

                  <div class="loyalty-suite-form__row">
                    <span class="loyalty-suite-form__row-label">
                      {{ $t('conditionCompletionOrder') }}
                      <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                        <q-tooltip anchor="top right" self="top right">
                          {{ $t('rankCompletionOrderHint') }}
                        </q-tooltip>
                      </q-icon>
                    </span>
                    <q-select v-model="rank.condition_order" :options="conditionOrderOptions" emit-value map-options
                      fill-input input-debounce="0" outlined>
                      <template v-slot:no-option>
                        <q-item>
                          <q-item-section class="text-grey">{{ $t('noResultsFound') }}</q-item-section>
                        </q-item>
                      </template>

                      <template v-slot:option="scope">
                        <q-item v-bind="scope.itemProps">
                          <q-item-section>
                            <q-item-label>{{ scope.opt.label }}</q-item-label>
                          </q-item-section>
                          <q-item-section side>
                            <q-icon name="info_outline" class="loyalty-suite-form__select-info" size="18px">
                              <q-tooltip anchor="top right" self="top right">
                                {{ $t(`opt_${scope.opt.value}`) }}
                              </q-tooltip>
                            </q-icon>
                          </q-item-section>
                        </q-item>
                      </template>
                    </q-select>
                  </div>

                  <Conditions v-model="rank.conditions" :changeLoading="changeLoading"
                    :conditionsFields="conditionsFields" :postType="'rank'" :currency="currency" />

                  <Rewards v-model="rank.rewards" :changeLoading="changeLoading" :rewardsFields="rewardsFields"
                    :postType="'rank'" :currency="currency" />

                  <div v-if="rankSet.ranks.length > 1"
                    class="loyalty-suite-form__row loyalty-suite-form__row_tab-action">
                    <q-btn color="negative" :loading="changeLoading" @click="deleteIndex(index)">
                      {{ $t('deleteRank') }}
                    </q-btn>
                  </div>
                </q-tab-panel>
              </q-tab-panels>
            </div>

            <Library v-if="activeRankIndex !== null" v-model="rankSet.ranks[activeRankIndex].icon"
              v-model:showLibrary="showLibrary" v-model:selectedTab="currentTab" @update:modelValue="setIcon" />

            <div class="loyalty-suite-form__action">
              <q-btn v-if="isEditing" class="loyalty-suite-form__action-delete" :label="$t('deleteRankSet')"
                @click="confirmDelete = true" color="negative" :loading="changeLoading" />
              <q-btn type="submit" :label="isEditing ? $t('saveRankSet') : $t('addRankSet')" :loading="changeLoading"
                color="primary" />
            </div>

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

            <q-dialog v-model="deactivate">
              <q-card>
                <q-card-section>
                  <span>{{ $t('rankSetDeactivation') }}</span>
                </q-card-section>
                <q-card-actions align="center">
                  <q-btn :label="$t('ok')" color="primary" :loading="changeLoading" v-close-popup />
                </q-card-actions>
              </q-card>
            </q-dialog>

            <q-dialog v-model="confirmDelete">
              <q-card>
                <q-card-section>
                  <span>{{ $t('rankSetDelete') }}</span>
                  <span>{{ $t('affectMembers') }}</span>
                </q-card-section>
                <q-card-actions align="center">
                  <q-btn :label="$t('cancel')" color="negative" v-close-popup />
                  <q-btn :label="$t('delete')" color="primary" v-close-popup @click="deleteRankSet" />
                </q-card-actions>
              </q-card>
            </q-dialog>

            <q-dialog v-model="confirmDeleteRank">
              <q-card>
                <q-card-section>
                  <span>{{ $t('rankDelete') }}</span>
                  <span>{{ $t('affectMembers') }}</span>
                </q-card-section>
                <q-card-actions align="center">
                  <q-btn :label="$t('cancel')" color="negative" v-close-popup />
                  <q-btn :label="$t('delete')" color="primary" v-close-popup @click="removeRank()" />
                </q-card-actions>
              </q-card>
            </q-dialog>

            <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 />
                  <q-btn :label="$t('discardChanges')" color="primary" v-close-popup @click="navigateBack" />
                </q-card-actions>
              </q-card>
            </q-dialog>

            <q-dialog v-model="ranksLimitDialog">
              <q-card>
                <q-card-section>
                  <span>{{ $t('ranksLimitTitle') }}</span>
                </q-card-section>
                <q-card-actions align="center">
                  <q-btn :label="$t('ok')" color="primary" v-close-popup />
                  <q-btn color="positive" :label="$t('getPRO')" :href="getProLink" target="_blank" v-close-popup />
                </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 { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import Conditions from '../../components/Conditions.vue';
import Rewards from '../../components/Rewards.vue';
import Library from '../../components/Library.vue';
import WpMediaUploader from '../../components/WpMediaUploader.vue';
import Editor from '../../components/Editor.vue';

export default defineComponent({
  components: { Conditions, Rewards, Library, Editor, WpMediaUploader },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const changeLoading = ref(false);
    const originalRankSet = ref<string | null>(null);
    const confirmLeave = ref(false);
    const activeTab = ref(0);
    const isEditing = computed(() => !!route.params.id);
    const loading = ref(true);
    const apiRoutes = window.loyalty_suite_admin_data.apiRoutes;
    const nonce = window.loyalty_suite_admin_data.nonce;
    const confirmDelete = ref(false);
    const confirmDeleteRank = ref(false);
    const rankToDelete = ref<number | null>(null);
    const deactivate = ref(false);
    const error = ref<string | null>(null);
    const addError = ref<string | null>(null);
    const showLibrary = ref(false);
    const currentTab = ref('ranks');
    const currency = ref({ symbol: '$' });
    const isPro = window.loyalty_suite_admin_data.isPro;
    const getProLink = window.loyalty_suite_admin_data.getProLink;
    const ranksLimitDialog = ref(false);
    const activeRankIndex = ref<number | null>(null);
    const { t } = useI18n();
    const conditionsFields = ref<Array<{
      key: string;
      type: string;
      options?: Array<{ value: string; label: string }>;
      dependency?: string[];
    }>>([]);
    const rewardsFields = ref<Array<{
      key: string;
      type: string;
      options?: Array<{ value: string; label: string }>;
      dependency?: string[];
    }>>([]);
    const conditionOrderOptions = ref([
      { value: 'sequential', label: t('sequentialOrder') },
      { value: 'any', label: t('anyOrder') },
    ]);
    const rankSetOrderOptions = ref([
      { value: 'sequential', label: t('sequentialOrder') },
      { value: 'any', label: t('anyOrder') },
    ]);

    const rankSet = ref<{
      id: Number | null,
      name: string,
      description: string,
      active: boolean,
      order: string,
      show: boolean,
      ranks: {
        id: Number | null,
        name: string,
        image_type: string,
        image: number | null,
        icon: File | null;
        previewUrl: string | null,
        previewName: string | null,
        fileError: boolean,
        condition_order: string,
        conditions: Array<Record<string, any>>,
        rewards: Array<Record<string, any>>
      }[];
    }>({
      id: !isNaN(Number(route.params.id)) ? Number(route.params.id) : null,
      name: '',
      description: '',
      active: true,
      order: 'sequential',
      show: true,
      ranks: [
        {
          id: null,
          name: '',
          image_type: 'icon',
          image: null,
          icon: null,
          previewUrl: null,
          previewName: null,
          fileError: false,
          condition_order: 'sequential',
          conditions: [],
          rewards: [],
        }
      ]
    });

    const goBack = () => {
      if (isDirty.value) {
        confirmLeave.value = true;
        return;
      }

      navigateBack();
    };

    const navigateBack = () => {
      if (window.history.length > 1) {
        router.back();
      } else {
        router.push('/ranks/list');
      }
    };

    const isDirty = computed(() => {
      return JSON.stringify(rankSet.value) !== originalRankSet.value;
    });

    const confirmDeactivation = (value: boolean) => {
      if (!value) {
        deactivate.value = true;
      }
    };

    const deleteIndex = (index: number) => {
      rankToDelete.value = index;
      confirmDeleteRank.value = true;
    };

    const addRank = () => {
      if (!isPro && rankSet.value.ranks.length >= 3) {
        ranksLimitDialog.value = true;
        return;
      }

      rankSet.value.ranks.push({
        id: null,
        name: '',
        image_type: 'icon',
        image: null,
        icon: null,
        previewUrl: null,
        previewName: null,
        fileError: false,
        condition_order: 'sequential',
        conditions: [],
        rewards: [],
      });
      activeTab.value = rankSet.value.ranks.length - 1;
    };

    const removeRank = () => {
      if (rankToDelete.value !== null) {
        rankSet.value.ranks.splice(rankToDelete.value, 1);
        activeTab.value = Math.max(0, activeTab.value - 1);
        rankToDelete.value = null;
      }
    };

    const validateForm = (): boolean => {
      const currentTabIndex = activeTab.value;
      if (!isTabValid(currentTabIndex)) return false;

      for (let i = 0; i < rankSet.value.ranks.length; i++) {
        if (!isTabValid(i)) {
          activeTab.value = i;
          return false;
        }
      }

      return true;
    };

    const isTabValid = (index: number): boolean => {
      const rank = rankSet.value.ranks[index];

      if (!rank.name || rank.name.trim() === '') {
        return false;
      }

      return true;
    };

    const setImage = (id: number, index: number) => {
      rankSet.value.ranks[index].image = id;
    };

    const imageTypeOptions = ref([
      { value: 'icon', label: t('icon') },
      { value: 'image', label: t('image') },
    ]);

    const getSelectedImageType = (index: number) => {
      return computed({
        get: () => {
          return (
            imageTypeOptions.value.find(
              option => option.value === rankSet.value.ranks[index].image_type
            ) || imageTypeOptions.value[0]
          );
        },
        set: (newValue) => {
          rankSet.value.ranks[index].image_type = newValue?.value || 'icon';
        }
      });
    };

    const removeIcon = (index: number) => {
      rankSet.value.ranks[index].icon = null;
      rankSet.value.ranks[index].previewUrl = null;
      rankSet.value.ranks[index].previewName = null;
    };

    const openLibrary = (index: number) => {
      activeRankIndex.value = index;
      showLibrary.value = true;
    };

    const setIcon = (icon: File) => {
      if (activeRankIndex.value === null) return;

      const rank = rankSet.value.ranks[activeRankIndex.value];
      rank.icon = icon;
      rank.previewUrl = URL.createObjectURL(icon);
      rank.previewName = icon.name;

      showLibrary.value = false;
      activeRankIndex.value = null;
    };

    const fetchRankSet = async () => {
      if (!isEditing.value) return;

      try {
        const buildApiUrl = (base, params = {}) => {
          const url = new URL(base, window.location.origin);
          Object.entries(params).forEach(([key, value]) => {
            if (value !== undefined && value !== null && value !== '') {
              url.searchParams.set(key, value);
            }
          });
          return url.toString();
        };

        const response = await fetch(
          buildApiUrl(apiRoutes.admin.rank, {
            id: Number(route.params.id),
          }),
          {
            method: 'GET',
            headers: {
              'X-WP-Nonce': nonce,
              'Content-Type': 'application/json',
            },
            credentials: 'same-origin',
          }
        );

        if (!response.ok) {
          throw new Error(`API Error: ${response.status} ${response.statusText}`);
        }

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

        rankSet.value.id = Number(route.params.id) ?? null,
        rankSet.value.name = data.rank_set.name;
        rankSet.value.description = data.rank_set.description;
        rankSet.value.active = data.rank_set.active;
        rankSet.value.order = data.rank_set.order;
        rankSet.value.show = data.rank_set.show;
        rankSet.value.ranks = data.rank_set.ranks.map((rank: any) => ({
          id: rank.id,
          name: rank.name,
          image_type: rank.image_type || 'icon',
          image: Number(rank.image) || null,
          icon: rank.icon,
          previewUrl: rank.icon_preview || null,
          previewName: rank.icon_filename || null,
          fileError: false,
          condition_order: rank.condition_order || 'sequential',
          conditions: Array.isArray(rank.conditions)
            ? rank.conditions
            : [],
          rewards: Array.isArray(rank.rewards)
            ? rank.rewards
            : [],
        }));
      } catch (err) {
        error.value = err instanceof Error ? err.message : t('couldNotFetchData');
        console.error('API Error:', error.value);
      }
    };

    const deleteRankSet = async () => {
      try {
        changeLoading.value = true;

        const response = await fetch(apiRoutes.admin.rank_delete, {
          method: 'DELETE',
          headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': nonce
          },
          body: JSON.stringify({ id: Number(route.params.id) })
        });

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

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

        router.push('/ranks/list');
      } catch (err) {
        error.value = err instanceof Error ? err.message : 'Error deleting rank set';
      } finally {
        changeLoading.value = false;
      }
    }

    const submitForm = async () => {
      if (!validateForm()) {
        changeLoading.value = false;
        return;
      }

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

        if (rankSet.value.id !== null) {
          formData.append('id', String(rankSet.value.id));
        }
        formData.append('name', rankSet.value.name);
        formData.append('description', rankSet.value.description);
        formData.append('active', String(rankSet.value.active));
        formData.append('order', String(rankSet.value.order));
        formData.append('show', String(rankSet.value.show));

        rankSet.value.ranks.forEach((rank, i) => {
          formData.append(`ranks[${i}][id]`, String(rank.id));
          formData.append(`ranks[${i}][name]`, rank.name);
          formData.append(`ranks[${i}][condition_order]`, rank.condition_order);
          formData.append(`ranks[${i}][conditions]`, JSON.stringify(rank.conditions));
          formData.append(`ranks[${i}][rewards]`, JSON.stringify(rank.rewards));
          formData.append(`ranks[${i}][image_type]`, rank.image_type);
          formData.append(`ranks[${i}][image]`, String(rank.image));
          if (rank.icon) {
            formData.append(`ranks[${i}][icon]`, rank.icon);
          }
        });

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

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

        if (data.error) {
          addError.value = data.error;
          return;
        }

        router.push('/ranks/list');
      } catch (err) {
        error.value = err instanceof Error ? err.message : 'Error submitting data';
      } finally {
        changeLoading.value = false;
      }
    }

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

        if (!response.ok) {
          throw new Error(`API Error: ${response.status} ${response.statusText}`);
        }

        const data = await response.json();
        conditionsFields.value = Array.isArray(data) ? data : [];
      } catch (err) {
        error.value = err instanceof Error ? err.message : t('couldNotFetchData');
        console.error('API Error:', error.value);
      }
    };

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

        if (!response.ok) {
          throw new Error(`API Error: ${response.status} ${response.statusText}`);
        }

        const data = await response.json();
        rewardsFields.value = Array.isArray(data) ? data : [];
      } catch (err) {
        error.value = err instanceof Error ? err.message : t('couldNotFetchData');
        console.error('API Error:', error.value);
      }
    };

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

        if (!response.ok) {
          throw new Error(`API Error: ${response.status} ${response.statusText}`);
        }

        const data = await response.json();
        currency.value = data;
      } catch (err) {
        error.value = err instanceof Error ? err.message : t('couldNotFetchData');
        console.error('API Error:', error.value);
      }
    };

    onBeforeMount(async () => {
      try {
        await Promise.all([fetchConditions(), fetchRewards(), fetchRankSet(), fetchCurrency()]);
      } catch (err) {
        console.error('Api error:', err);
      } finally {
        loading.value = false;
      }

      watch(rankSet, (newVal) => {
        if (originalRankSet.value === null) {
          originalRankSet.value = isEditing.value
            ? JSON.stringify(newVal)
            : JSON.stringify({
              id: Number(route.params.id) ?? null,
              name: '',
              description: '',
              active: true,
              order: 'sequential',
              show: true,
              ranks: [
                {
                  id: null,
                  name: '',
                  image_type: 'icon',
                  image: null,
                  icon: null,
                  previewUrl: null,
                  previewName: null,
                  fileError: false,
                  condition_order: 'sequential',
                  conditions: [],
                  rewards: [],
                }
              ]
            });
        }
      }, { deep: true, immediate: true });
    });

    return {
      rankSet,
      activeTab,
      error,
      addError,
      confirmLeave,
      navigateBack,
      confirmDelete,
      confirmDeleteRank,
      deactivate,
      confirmDeactivation,
      isEditing,
      loading,
      changeLoading,
      goBack,
      addRank,
      deleteRankSet,
      deleteIndex,
      removeRank,
      removeIcon,
      submitForm,
      conditionsFields,
      rewardsFields,
      conditionOrderOptions,
      showLibrary,
      openLibrary,
      currentTab,
      setIcon,
      activeRankIndex,
      currency,
      setImage,
      getSelectedImageType,
      imageTypeOptions,
      isPro,
      ranksLimitDialog,
      getProLink,
      rankSetOrderOptions
    };
  }
});
</script>

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

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

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

  .loyalty-suite-form {
    width: 700px;

    &__conditions {
      padding: 0;
      margin: 10px 0 0 0;
      border-radius: 0;
      box-shadow: none;
    }

    &__rewards {
      padding: 0;
      margin: 10px 0 0 0;
      border-radius: 0;
      box-shadow: none;
    }
  }
}
</style>
