<template>
    <div class="row" v-if="authStore.isAdmin">
        <div class="col">
            <div class="row">
                <div class="col ml-md-3 ml-0 mt-md-0 mt-3 bg-white padding-15">
                    <div class="row">
                        <div class="col">
                            <div class="row m-b-10">
                                <div class="col">
                                    <div class="font-heading fs-16 all-caps bold m-b-15">Add Voucher Select</div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col">
                                    <validation-wrapper-component selectable :validator="v$.voucherCode">
                                        <label>Voucher Options</label>
                                        <selectable-component :endpoint="route('api.voucher.campaigns.list') + '?filters=' + JSON.stringify({ is_display: 1 })" :section="section" valueColumn="name" :labelColumn="['name', 'description']" v-model="voucherCode"></selectable-component>
                                    </validation-wrapper-component>
                                </div>
                            </div>
                            <div class="row m-l-0 m-r-0" style="height: 20px">
                                <i class="fa fa-spinner fa-spin m-b-5" v-show="isLoading && voucherIsChecking"></i>
                                <span class="text-danger" v-if="voucherCodeFailedReason">{{ voucherCodeFailedReason }}</span>
                                <span class="text-success" v-if="voucherCodeFailedReason === '' && voucherFetched">Voucher added</span>
                            </div>
                            <div class="row">
                                <div class="col">
                                    <button type="button" class="btn btn-block p-t-10 p-b-10 p-r-35 p-l-35 btn-success b-rad-none" @click="submitForm">Add Voucher</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useAuthStore } from '@/stores/auth';
import { useQueueStore } from '@/stores/queue';
import { useFormHandler } from '@/composables/useFormHandler';
import { useVuelidate } from '@vuelidate/core';
import { required } from '@vuelidate/validators';
import route from '@/general/functions/router';

interface Props {
    id: string;
    section: string;
    options: any[];
}

const props = defineProps<Props>();

const authStore = useAuthStore();
const queueStore = useQueueStore();
const { submit, isLoading } = useFormHandler({ section: props.section });

const section = props.section;
const voucherCode = ref('');
const voucherCodeFailedReason = ref('');
const voucherFetched = ref(false);
const voucherIsChecking = ref(false);

const rules = { voucherCode: { required } };
const v$ = useVuelidate(rules, { voucherCode });

const reset = () => {
    voucherFetched.value = false;
    voucherCodeFailedReason.value = '';
};

const submitForm = async () => {
    const isValid = await v$.value.$validate();
    if (!isValid) return;

    reset();
    voucherIsChecking.value = true;

    submit(route('api.voucher.create'), 'post', section, false, false, {
        voucherCode: voucherCode.value,
        userId: props.id
    }, {
        successHandler: (response: any) => {
            if (response.payload.data && response.payload.data.voucher_id !== undefined) {
                voucherFetched.value = true;
                queueStore.reloadList({ name: 'customerVouchersListSection' });
                voucherCode.value = '';
                v$.value.$reset();
            } else {
                voucherFetched.value = false;
                voucherCodeFailedReason.value = response.payload.data?.reason || 'Voucher Invalid';
            }
            queueStore.reloadList({ name: 'voucherCampaignsSection' });
            voucherIsChecking.value = false;
        },
        errorHandler: () => {
            voucherCodeFailedReason.value = 'Something went wrong, please report this to tech';
            voucherFetched.value = false;
            voucherIsChecking.value = false;
        }
    });
};
</script>
