<template>
    <div class="row" @keyup.enter="importToSystem">
        <div class="col">
            <loading-component style="height: 200px; top: 0;" key="1" color="success" v-show="isLoading"></loading-component>
            <div class="row" v-show="!isLoading">
                <div class="col">
                    <div class="row">
                        <div class="col">
                            <file-input-component :key="fileInputKey" :validator="v$.parameters.files" v-model="parameters.files" :withMeta="true">
                                <template #label>
                                    <div class="font-heading fs-11 text-primary all-caps">Import Purchase Order PDF</div>
                                </template>
                            </file-input-component>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col">
                            <button type="button"
                                class="btn btn-sm btn-block p-t-10 p-b-10 p-r-35 p-l-35 btn-success b-rad-none"
                                @click="importToSystem"
                                :disabled="isExporting || isImporting">
                                {{ isImporting ? 'Uploading...' : 'Upload' }}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

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

const props = defineProps<{
    section: string;
    bookingId: number;
}>();

const { isLoading: formLoading, parameters, submit } = useFormHandler({
    section: props.section,
    data: {
        files: [],
        products: []
    }
});
const queueStore = useQueueStore();

const isExporting = ref(false);
const isImporting = ref(false);
const fileInputKey = ref(0);

const files = ref([]);

const rules = {
    parameters: {
        files: { required }
    }
};

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

const isLoading = computed(() => formLoading.value);

const escapeCSV = (value: any) => {
    if (value === null || value === undefined) return '';
    const str = value.toString();
    if (str.includes(',') || str.includes('"') || str.includes('\n')) {
        return `"${str.replace(/"/g, '""')}"`;
    }
    return str;
};

const resetFileInput = () => {
    parameters.value.files = [];
    v$.value.$reset();
    fileInputKey.value++;
};

const onComplete = (data: any) => {
    queueStore.reloadList({ name: 'bookingDetailSection' });
    fileInputKey.value++;
    const bookingChannel = `admin.pdf.1688.processing.${data.bookingId}`;
    if ((window as any).Echo) {
        (window as any).Echo.leave(bookingChannel);
    }
};

const successHandler = (response: any, section?: string) => {
    if (props.section + 'PDFImport' === section) {
        if (Array.isArray(response.payload) && response.payload.length === 0) {
            const bookingChannel = `admin.pdf.1688.processing.${props.bookingId}`;
            if ((window as any).Echo) {
                (window as any).Echo.channel(bookingChannel)
                    .listen('ETLPurchaseOrderTransactionCompleteEvent', onComplete);
            }
            isImporting.value = false;
            resetFileInput();
        } else {
            isImporting.value = false;
            fileInputKey.value++;
        }
        queueStore.reloadList({ name: 'bookingDetailSection' });
    } else if (props.section + 'PDFExport' === section) {
        try {
            const BOM = '\uFEFF';
            let csvContent = "stock code,description,quantity,unit price\r\n";
            response.payload.forEach((item: any) => {
                const formattedRow = [
                    item.stockCode,
                    escapeCSV(item.description),
                    item.quantity,
                    item.unit_price
                ].join(',');
                csvContent += formattedRow + "\r\n";
            });

            const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.setAttribute("download", "order_details.csv");
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            parameters.value.products = response.payload;
        } catch (e) {
            console.error("Export failed:", e);
            alert("Export failed. Please try again.");
        } finally {
            isExporting.value = false;
        }
    }
};

const errorHandler = (_response: any, statusCode: number, sectionName?: string) => {
    isExporting.value = false;
    isImporting.value = false;
};

// These methods are available for template usage if needed (currently only importToSystem is visible in non-commented template)
const exportToCSV = () => {
    parameters.value.products = [];
    if (isExporting.value) return;
    isExporting.value = true;
    submit(route('api.transaction.po.etl', props.bookingId), 'post', props.section + 'PDFExport', true, false, parameters.value, { successHandler, errorHandler });
};

const importToSystem = () => {
    if (isImporting.value) return;
    isImporting.value = true;
    submit(route('api.transaction.po.import', props.bookingId), 'post', props.section + 'PDFImport', true, true, parameters.value, { successHandler, errorHandler });
};
</script>
