<template>
    <div class="row mt-3 mt-md-0">
        <div class="col">
            <div class="row">
                <div class="col">
                    <div class="row align-items-end m-b-10">
                        <div class="col">
                            <div class="font-heading all-caps fs-10">Supplier:</div>
                        </div>
                        <div class="col-auto">
                            <div class="font-heading fs-10">{{ supplier.name }}</div>
                        </div>
                    </div>
                    <div class="row align-items-end m-b-5 text-info">
                        <div class="col">
                            <div class="font-heading all-caps fs-10">Order Total:</div>
                        </div>
                        <div class="col-auto text-right">
                            <div class="font-heading fs-11">{{ currency.short_code }} {{ formatAmount(total) }}</div>
                        </div>
                    </div>
                    <div class="row align-items-end m-b-5 text-info">
                        <div class="col">
                            <div class="font-heading all-caps fs-10">Rate:</div>
                        </div>
                        <div class="col-auto text-right">
                            <div class="font-heading fs-11">{{ parameters.rate }}</div>
                        </div>
                    </div>
                    <div class="row align-items-end m-b-10 text-success">
                        <div class="col">
                            <div class="font-heading all-caps fs-10">Payment Total:</div>
                        </div>
                        <div class="col-auto text-right">
                            <div class="font-heading bold">MYR {{ formatAmount(paymentTotal) }}</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col">
                    <validation-wrapper-component :validator="v$.parameters.rate">
                        <label class="all-caps">Purchase Rate</label>
                        <input v-model.lazy="parameters.rate" v-money3="exchangeRate" type="text" class="form-control">
                    </validation-wrapper-component>
                </div>
            </div>
            <div v-if="paymentTotal > 0" class="row">
                <div class="col">
                    <button class="btn btn-xs btn-success b-rad-none p-t-5 p-b-5 all-caps fs-10 btn-block" :disabled="isCreating" @click="submitForm">
                        Create Order <span v-if="isCreating" class="spinner"></span>
                    </button>
                    <button class="btn btn-xs btn-complete b-rad-none p-t-5 p-b-5 all-caps fs-10 w-100" @click="generateMockWhiteForm">
                        Create Mock Up White Form
                    </button>
                </div>
            </div>
            <modal-component size="small" id="">
                <div class="row">
                    <div class="col">
                        <div class="row">
                            <div class="col">
                                <div class="row">
                                    <div class="col">
                                        <div class="font-heading fs-10">Download Supplier Order Summary</div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col">
                                        <button class="btn btn-sm btn-success b-rad-none">Download</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col"></div>
                        </div>
                    </div>
                </div>
            </modal-component>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import useVuelidate from '@vuelidate/core';
import { required } from '@vuelidate/validators';
import { Money3Directive } from 'v-money3';
import route from '@/general/functions/router';
import { useCrudStore } from '@/stores/crud';
import { useQueueStore } from '@/stores/queue';
import { useRequest } from '@/composables/useRequest';

const props = defineProps<{
    payments: Array<Record<string, any>>;
    currency: Record<string, any>;
    supplier: Record<string, any>;
}>();

const crudStore = useCrudStore();
const queueStore = useQueueStore();
const exchangeRate = { decimal: '.', thousands: '', precision: 5 };
const { submit } = useRequest();

const isCreating = ref(false);
const parameters = reactive({
    rate: 0 as number | string
});

const rules = computed(() => ({
    parameters: {
        rate: { required }
    }
}));

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

const total = computed(() => {
    return props.payments.reduce((grandTotal, currentValue) => {
        const refundTotal = currentValue.transaction_refunds.reduce((totalRefund: number, refundTransaction: Record<string, any>) => {
            if (refundTransaction.status === 2) {
                return totalRefund + refundTransaction.original_amount;
            }
            return totalRefund;
        }, 0);

        return grandTotal + currentValue.original_amount - refundTotal;
    }, 0);
});

const paymentTotal = computed(() => {
    const numericRate = parseFloat(String(parameters.rate));
    return total.value && numericRate ? total.value * (1 / numericRate) : 0;
});

const formatAmount = (value: number) => {
    return (Math.round((Number(value) + Number.EPSILON) * 100) / 100)
        .toFixed(2)
        .toString()
        .replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

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

    isCreating.value = true;

    await submit(
        route('api.transaction.supplier.create', props.supplier.id),
        'post',
        'pendingOrdersSection',
        true,
        true,
        {
            payments: props.payments,
            rate: parameters.rate
        },
        {
            validate: () => v$.value.$validate(),
            successHandler: () => {
                queueStore.reloadList({ name: 'pendingOrdersSection' });
                parameters.rate = 0;
                isCreating.value = false;
            },
            errorHandler: () => {
                isCreating.value = false;
            }
        }
    );
};

const generateMockWhiteForm = async () => {
    const paymentIds = props.payments.map((payment) => payment.id);
    const url = `${route('whiteForm.mockUp', props.supplier.id)}?rate=${parameters.rate}&payments=${JSON.stringify(paymentIds)}`;

    if (window.LARAVEL_VAPOR_ENABLED) {
        const response = await crudStore.crudRequest({ endpoint: url, method: 'get' });
        const success = response.ok;
        const payload = await response.json();

        if (success && payload.src) {
            window.open(payload.src, '_blank');
        }
        return;
    }

    window.open(url, '_blank');
};
</script>

<script lang="ts">
export default {
    directives: {
        money: Money3Directive
    }
};
</script>

<style scoped>
.spinner {
    border: 2px solid rgba(0, 0, 0, 0.1);
    border-left-color: #000;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    animation: spin 1s linear infinite;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

@keyframes spin {
    0% {
        transform: translate(-50%, -50%) rotate(0deg);
    }
    100% {
        transform: translate(-50%, -50%) rotate(360deg);
    }
}
</style>
