<template>
    <div class="row">
        <div class="col">
            <loading-component style="height: 50px; top: 0;" key="1" color="success" v-show="isLoading"></loading-component>
            <div class="row" v-show="!isLoading">
                <div class="col">
                    <div class="row m-b-20 parentContainer align-items-center p-b-10 b-b" style="border-color: #e0e0e0 !important;">
                        <div class="col">
                            <validation-wrapper-component :validator="v$.parameters.code_binding_days">
                                <label>Code Binding Days</label>
                                <input
                                    type="number"
                                    class="form-control"
                                    v-model.number="parameters.code_binding_days"
                                    min="1"
                                    max="365"
                                    placeholder="e.g., 30">
                            </validation-wrapper-component>
                        </div>
                        <div class="col-auto">
                            <div class="btn btn-sm btn-success b-rad-none" @click="submitForm">
                                <i class="fa fa-save m-r-5"></i>Save
                            </div>
                        </div>
                    </div>
                    <div class="row m-b-5 animate__animated animate__fadeInUpBig animate__fast" v-if="error">
                        <div class="col">
                            <small class="bold fs-10 text-danger">{{ error }}</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { useVuelidate } from '@vuelidate/core';
import { integer, maxValue, minValue, required } from '@vuelidate/validators';
import { useCrudStore } from '@/stores/crud';
import { useUiStore } from '@/stores/ui';
import { useRequest } from '@/composables/useRequest';
import route from '@/general/functions/router';

interface Props {
    section?: string;
}

const props = withDefaults(defineProps<Props>(), {
    section: 'affiliateSettingsSection'
});

const uiStore = useUiStore();
const crudStore = useCrudStore();
const { submit } = useRequest();

const error = ref('');
const parameters = reactive({
    code_binding_days: 30
});

const rules = {
    parameters: {
        code_binding_days: {
            required,
            integer,
            minValue: minValue(1),
            maxValue: maxValue(365)
        }
    }
};

const v$ = useVuelidate(rules, { parameters });

const isLoading = computed(() => uiStore.isLoading(props.section));

const loadSettings = async () => {
    uiStore.toggleLoading(props.section, true);
    error.value = '';

    try {
        const response = await crudStore.crudRequest({
            endpoint: route('api.affiliate.settings.get'),
            method: 'get'
        });

        const data = await response.json();

        if (!response.ok) {
            error.value = data?.message || 'Failed to load settings';
            return;
        }

        if (data && data.code_binding_days !== undefined) {
            parameters.code_binding_days = parseInt(data.code_binding_days, 10);
        }
    } catch {
        error.value = 'Failed to load settings';
    } finally {
        uiStore.toggleLoading(props.section, false);
    }
};

const submitForm = async () => {
    error.value = '';
    await submit(
        route('api.affiliate.settings.update'),
        'post',
        props.section,
        true,
        true,
        parameters,
        {
            validate: () => v$.value.$validate(),
            errorHandler: (data, statusCode, sectionName) => {
                error.value = data?.message || 'Failed to update settings';
            }
        }
    );
};

onMounted(() => {
    loadSettings();
});
</script>
