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

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

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

// Loading states
const checkConnectionLoading = ref(false);
const resetTokenLoading = ref(false);

// Message states
const connectionMessage = ref('');
const connectionMessageType = ref<'success' | 'error'>('success');
const tokenMessage = ref('');
const tokenMessageType = ref<'success' | 'error'>('success');

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

const checkApiConnection = async () => {
    try {
        // Reset message
        connectionMessage.value = '';

        // Set loading
        checkConnectionLoading.value = true;

        // Call the REST API to check connection
        const response = await Axios.post(`${config.rest.endpoints.settings}/check_connection`);

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

        // Show success message
        connectionMessage.value = $gettext('API connection is working correctly!');
        connectionMessageType.value = 'success';
    } catch (error) {
        // Show error
        console.error('Error checking API connection:', error);

        connectionMessage.value = $gettext('API connection failed. You may need to reset your API token.');
        connectionMessageType.value = 'error';
    } finally {
        // Set loading
        checkConnectionLoading.value = false;
    }
};

const resetApiToken = async () => {
    try {
        // Reset message
        tokenMessage.value = '';

        // Set loading
        resetTokenLoading.value = true;

        // Call the REST API to reset token
        const response = await Axios.post(`${config.rest.endpoints.settings}/request_api_key_reset`);

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

        // Show success message
        tokenMessage.value = $gettext('Email has been sent to you! Please check your inbox.');
        tokenMessageType.value = 'success';
    } catch (error) {
        // Show error
        console.error('Error resetting API token:', error);

        tokenMessage.value = $gettext('There was an error while sending the email!');
        tokenMessageType.value = 'error';
    } finally {
        // Set loading
        resetTokenLoading.value = false;
    }
};
</script>

<template>
    <!-- API Connection wrapper -->
    <div 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">
        <!-- Check API Connection -->
        <div class="flex flex-col gap-3">
            <h3 class="text-lg font-semibold">{{ $gettext('API Connection') }}</h3>
            <p class="text-gray-600 text-sm">
                {{ $gettext('Test your API connection to ensure everything is working properly.') }}
            </p>
            <Button
                class="max-md:w-full self-start"
                type="primary"
                :text="$gettext('Check API Connection')"
                size="large"
                :disabled="isAccountExpired"
                :loading="checkConnectionLoading"
                @click.prevent="checkApiConnection"
            />
            <!-- Connection Message -->
            <div v-if="connectionMessage" class="mt-2">
                <p
                    :class="[
                        'text-sm font-medium',
                        connectionMessageType === 'success' ? 'text-green-600' : 'text-red-600',
                    ]"
                >
                    {{ connectionMessage }}
                </p>
            </div>
        </div>

        <!-- Separator -->
        <hr class="border-neutral-300" />

        <!-- Reset API Token -->
        <div class="flex flex-col gap-3">
            <h3 class="text-lg font-semibold">{{ $gettext('API Token') }}</h3>
            <p class="text-gray-600 text-sm">
                {{
                    $gettext(
                        'Reset your API token if you have problems with the connection. You will receive a link to reset the key in your email.'
                    )
                }}
            </p>
            <Button
                class="max-md:w-full self-start"
                type="danger"
                :text="$gettext('Reset API Token')"
                size="large"
                :disabled="isAccountExpired"
                :loading="resetTokenLoading"
                @click.prevent="resetApiToken"
            />
            <!-- Token Message -->
            <div v-if="tokenMessage" class="mt-2">
                <p :class="['text-sm font-medium', tokenMessageType === 'success' ? 'text-green-600' : 'text-red-600']">
                    {{ tokenMessage }}
                </p>
            </div>
        </div>
    </div>
</template>

<style scoped></style>
