<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-submission">
          <div class="loyalty-suite-submission__title">
            <q-btn icon="arrow_back" color="primary" class="loyalty-suite-form__back" @click="goBack" />
            <h1 class="loyalty-suite-submission__title-text">
              {{ $t('submissionEdit') }}
            </h1>
          </div>
          <q-form class="loyalty-suite-form" @submit.prevent="submitForm">
            <div class="loyalty-suite-form__section">
              <div class="loyalty-suite-form__row">
                <span class="loyalty-suite-form__row-label">
                  {{ $t('submissionSourceType') }}
                </span>
                <div class="loyalty-suite-form__row-value">
                  {{ $t(submission.source_type) }}
                </div>
              </div>
              <div class="loyalty-suite-form__row">
                <span class="loyalty-suite-form__row-label">
                  {{ $t('submissionSource') }}
                </span>
                <div class="loyalty-suite-form__row-value">
                  {{ submission.source }}
                </div>
              </div>
              <div class="loyalty-suite-form__row">
                <span class="loyalty-suite-form__row-label">
                  {{ $t('submissionConditionType') }}
                </span>
                <div class="loyalty-suite-form__row-value">
                  {{ $t(submission.condition_type) }}
                </div>
              </div>
              <div class="loyalty-suite-form__row">
                <span class="loyalty-suite-form__row-label">
                  {{ $t('submissionNetwork') }}
                </span>
                <div class="loyalty-suite-form__row-value">
                  {{ $t(submission.condition.rules.network.value) }}
                </div>
              </div>
              <div class="loyalty-suite-form__row">
                <span class="loyalty-suite-form__row-label">
                  {{ $t('submissionUser') }}
                </span>
                <div class="loyalty-suite-form__row-value">
                  {{ submission.user }}
                </div>
              </div>
              <div v-if="submission.condition_type === 'publish_content'"
                class="loyalty-suite-form__row loyalty-suite-form__row_full-width">
                <span class="loyalty-suite-form__row-label">
                  {{ $t('submissionRequirements') }}
                </span>
                <textarea class="loyalty-suite-form__row-textarea" rows="8" readonly
                  v-html="submission.condition.rules.publish_content_desc"></textarea>
              </div>
              <div v-if="submission.condition.rules.shared_link"
                class="loyalty-suite-form__row loyalty-suite-form__row_full-width">
                <span class="loyalty-suite-form__row-label">
                  {{ $t('submissionSharedLink') }}
                </span>
                <div class="loyalty-suite-form__row-value">
                  <a :href="submission.condition.rules.shared_link" target="_blank" rel="noopener" class="loyalty-suite-form__row-link">
                    {{ submission.condition.rules.shared_link }}
                  </a>
                </div>
              </div>
              <div v-if="submission.condition.rules.social_link"
                class="loyalty-suite-form__row loyalty-suite-form__row_full-width">
                <span class="loyalty-suite-form__row-label">
                  {{ $t('submissionSocialLink') }}
                </span>
                <div class="loyalty-suite-form__row-value">
                  <a :href="submission.condition.rules.social_link" target="_blank" rel="noopener" class="loyalty-suite-form__row-link">
                    {{ submission.condition.rules.social_link }}
                  </a>
                </div>
              </div>
              <div class="loyalty-suite-form__row loyalty-suite-form__row_full-width">
                <span class="loyalty-suite-form__row-label">
                  {{ $t('submissionUserAnswer') }}
                </span>
                <div class="loyalty-suite-form__row-value">
                  <template v-if="isUserAnswerLink">
                    <a :href="submission.user_answer" target="_blank" rel="noopener" class="loyalty-suite-form__row-link">
                      {{ submission.user_answer }}
                    </a>
                  </template>
                  <template v-else>
                    {{ submission.user_answer }}
                  </template>
                </div>
              </div>
              <div class="loyalty-suite-form__row">
                <span class="loyalty-suite-form__row-label">
                  {{ $t('submissionStatus') }}
                </span>
                <q-select v-model="selectedStatus" :options="statusOptions" fill-input input-debounce="0"
                  :rules="[() => !!selectedStatus || $t('requiredField')]" outlined>
                </q-select>
              </div>
            </div>

            <div class="loyalty-suite-form__action">
              <q-btn class="loyalty-suite-form__action-delete" :label="$t('delete')"
                @click="confirmDelete = true" color="negative" :loading="changeLoading" />
              <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>

            <q-dialog v-model="confirmDelete">
              <q-card>
                <q-card-section>
                  <span>{{ $t('submissionDelete') }}</span>
                  <span>{{ $t('affectMembersSubmission') }}</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" @click="deleteSubmission" />
                </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-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 Library from '../../components/Library.vue';

export default defineComponent({
  components: { Library },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const { t } = useI18n();
    const loading = ref(true);
    const changeLoading = ref(false);
    const originalSubmission = ref<string | null>(null);
    const confirmLeave = ref(false);
    const confirmDelete = ref(false);
    const error = ref<string | null>(null);
    const addError = ref<string | null>(null);
    const apiRoutes = window.loyalty_suite_admin_data.apiRoutes;
    const nonce = window.loyalty_suite_admin_data.nonce;

    const submission = ref<{
      id: number | null;
      user: string,
      user_id: number | null,
      user_answer: string,
      source: string,
      source_type: string,
      source_id?: number | null,
      status: string,
      condition: Array<[]>,
      condition_type: string
    }>({
      id: Number(route.params.id) ?? null,
      user: '',
      user_id: null,
      user_answer: '',
      source: '',
      source_type: '',
      source_id: null,
      status: '',
      condition: [],
      condition_type: '',
    });

    const statusOptions = ref([
      { value: 'pending', label: t('pending') },
      { value: 'rejected', label: t('rejected') },
      { value: 'approved', label: t('approved') }
    ]);

    const selectedStatus = computed({
      get: () => {
        return (
          statusOptions.value.find(option => option.value === submission.value.status) ||
          statusOptions.value[0]
        );
      },
      set: (newValue) => {
        submission.value.status = newValue?.value || 'pending';
      }
    });

    const isUserAnswerLink = computed(() => {
      return /^https?:\/\//.test(submission.value.user_answer);
    });

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

      navigateBack();
    };

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

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

    const fetchSubmission = async () => {
      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.submission, {
            id: Number(route.params.id),
          }),
          {
            method: 'GET',
            headers: {
              'X-WP-Nonce': nonce,
              'Content-Type': 'application/json',
            },
            credentials: 'same-origin',
          }
        );

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

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

        submission.value = {
          id: Number(route.params.id) ?? null,
          ...data.submission,
        };
      } catch (err) {
        error.value = err instanceof Error ? err.message : t('couldNotFetchData');
        console.error('API Error:', error.value);
      }
    };

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

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

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

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

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

        if (submission.value.id !== null) {
          formData.append('id', String(submission.value.id));
        }
        formData.append('status', submission.value.status);
        formData.append('condition_type', submission.value.condition_type);
        formData.append('condition_id', String(submission.value.condition.id));
        formData.append('source_id', String(submission.value.source_id));
        formData.append('source_type', submission.value.source_type);
        formData.append('user_id', String(submission.value.user_id));

        const response = await fetch(apiRoutes.admin.submission_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;
        }

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

    onBeforeMount(async () => {
      await Promise.all([fetchSubmission()]);
      loading.value = false;

      watch(submission, (newVal) => {
        if (originalSubmission.value === null) {
          originalSubmission.value = JSON.stringify(newVal);
        }
      }, { deep: true, immediate: true });
    });

    watch(() => route.params.id, fetchSubmission);

    return {
      changeLoading,
      loading,
      error,
      addError,
      confirmLeave,
      navigateBack,
      submission,
      confirmDelete,
      goBack,
      deleteSubmission,
      selectedStatus,
      statusOptions,
      isUserAnswerLink,
      submitForm
    };
  }
});
</script>

<style lang="scss" scoped>
.loyalty-suite-submission {
  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>
