<!-- My account settings tab -->
<script setup lang="ts">
import TextInput from '../form/TextInput.vue';
import Button from '../base/Button.vue';
import { inject, ref } from 'vue';
import { AppConfigType } from '~src/admin/types';
import Axios from '~src/shared/axios';
import { useNotificationStore } from '~src/admin/stores/useNotificationStore';
import { useGettext } from 'vue3-gettext';
import Toggle from '../form/Toggle.vue';

// Translations
const { $gettext } = useGettext();

// Get plugin config
const config: AppConfigType = inject('pluginConfig');

// Show notification
const { addNotification } = useNotificationStore();

// Input values
const loginValue = ref(config.settings.email);
const restUrl = ref(config.settings.rest_url);
const enableCategoryCreation = ref(config.settings.enable_category_creation);
const categoryCreationLimit = ref(config.settings.category_creation_limit);

// Handle errors
const errorRestURL = ref('');
const errorCategoryCreationLimit = ref('');

// Loading
const loading = ref(false);

const updateSettings = async () => {
    try {
        // Reset errors
        errorRestURL.value = '';

        // Set loading
        loading.value = true;

        // Validate the url
        if (restUrl.value.length > 0 && !restUrl.value.startsWith('http://') && !restUrl.value.startsWith('https://')) {
            errorRestURL.value = $gettext('Please enter a valid URL!');
            return;
        }

        // Validate the category creation limit
        if (categoryCreationLimit.value < 1) {
            errorCategoryCreationLimit.value = $gettext('Category creation limit must be greater than 0!');
            return;
        }

        // Prepare the body
        const body = {
            rest_url: restUrl.value,
            enable_category_creation: enableCategoryCreation.value,
            category_creation_limit: categoryCreationLimit.value,
        };

        // Call the REST API to save settings
        const response = await Axios.post(`${config.rest.endpoints.settings}/update_plugin`, body);

        // Check if the response is successful
        if (response.status !== 200 && !response.data.success) {
            throw new Error(`REST API error: ${response.status} - ${response.statusText}`);
        }

        // Show message
        addNotification({
            message: $gettext('Settings updated succesfully!'),
            type: 'success',
        });
    } catch (error) {
        // Show error
        console.error('Error fetching posts:', error);

        addNotification({
            message: $gettext('There was an error while updating the settings!'),
            type: 'danger',
        });
    } finally {
        // Set loading
        loading.value = false;
    }
};

// Account expired
const isAccountExpired = inject<boolean>('isAccountExpired');
</script>

<template>
    <!-- Inputs wrapper -->
    <form class="flex flex-col gap-5 md:max-w-[624px] px-5 md:px-10 py-5 bg-white border border-neutral-500 rounded-lg">
        <!-- Login -->
        <div class="flex flex-col md:flex-row items-baseline gap-1 md:gap-5 pointer-events-none">
            <label class="cursor-pointer md:min-w-[170px]" for="login">{{ $gettext('Login:') }}</label>
            <TextInput :disabled="true" name="login" v-model="loginValue" />
        </div>

        <!-- Enable category creation -->
        <div class="flex flex-col md:flex-row items-baseline gap-1 md:gap-5">
            <label class="cursor-pointer md:min-w-[170px]" for="enable_category_creation">
                {{ $gettext('Enable category creation:') }}
            </label>
            <Toggle
                :disabled="loading || isAccountExpired"
                v-model="enableCategoryCreation"
                :active-text="$gettext('Yes')"
                :inactive-text="$gettext('No')"
            />
        </div>

        <!-- Category creation limit -->
        <div class="flex flex-col md:flex-row items-baseline gap-1 md:gap-5">
            <label class="cursor-pointer md:min-w-[170px]" for="category_creation_limit">
                {{ $gettext('Category creation limit:') }}
            </label>
            <TextInput
                :disabled="loading || isAccountExpired"
                type="number"
                name="category_creation_limit"
                v-model="categoryCreationLimit"
                :error-msg="errorCategoryCreationLimit"
            />
        </div>

        <!-- Rest URL -->
        <div class="flex flex-col md:flex-row items-baseline gap-1 md:gap-5">
            <label class="cursor-pointer md:min-w-[170px]" for="rest_url">{{ $gettext('Rest URL:') }}</label>
            <TextInput
                :disabled="loading || isAccountExpired"
                type="url"
                name="rest_url"
                :error-msg="errorRestURL"
                v-model="restUrl"
            />
        </div>

        <!-- Button -->
        <Button
            class="max-md:w-full self-end"
            type="primary"
            :text="$gettext('Save changes')"
            size="large"
            :disabled="!restUrl.length || isAccountExpired"
            :loading
            @click.prevent="updateSettings"
        />
    </form>
</template>

<style scoped></style>
