<template>
    <div class="row m-b-20">
        <div class="col">
            <div class="row">
                <div class="col">
                    <div class="row m-l-0 m-r-0 parentContainer">
                        <div class="col-12 col-md mb-2 mb-md-0 p-l-3 p-r-3 p-md-0">
                            <validation-wrapper-component :validator="v$.parameters.startDate">
                               <label class="all-caps">
                                    Start Date
                                    <span
                                        class="ml-2 text-primary"
                                        data-toggle="tooltip"
                                        data-placement="right"
                                        data-html="true"
                                        data-custom-class="tooltip-report-export"
                                        title="
                                            <div>
                                                1. Sales Invoice Report → Filters by Payment Date<br/>
                                                2. Customers Report → Filters by E-Invoice Requested Date<br/>
                                                3. 01D - Sales Deposit Received [AR DEPOSIT ENTRY] → Filters by Payment Date<br/>
                                                4. 01R - RECEIVE PAYMENT [AR RECEIVE PAYMENT] → Filters by Payment Date<br/>
                                                5. Credit Note Report → Filters by Credit Note Created Date<br/>
                                                6. 01DRW - Sales Deposit by Wallet [AR PAYMENT ENTRY] → Filters by Created Date<br/>
                                                7. 01DRF - Sales Deposit by Wallet [AR REFUND ENTRY] → Filters by Created Date<br/>
                                                8. 01DD - Sales Deposit by Wallet [AR DEPOSIT ENTRY] → Filters by Created Date<br/>
                                                9. WALLET TOP UP REPORT [Wallet Deposit Received] → Filters by Top Up Date<br/>
                                            </div>
                                        ">
                                        <i class="fa fa-info-circle"></i>
                                    </span>
                                </label>
                                <date-picker-component :parameters="parameters" v-model.lazy="parameters.startDate"></date-picker-component>
                            </validation-wrapper-component>
                        </div>
                        <div class="col-12 col-md mb-2 mb-md-0 p-l-3 p-r-3 p-md-0">
                            <validation-wrapper-component :validator="v$.parameters.endDate">
                                <label class="all-caps">
                                    End Date
                                    <span
                                        class="ml-2 text-primary"
                                        data-toggle="tooltip"
                                        data-placement="right"
                                        data-html="true"
                                        data-custom-class="tooltip-report-export"
                                        title="
                                            <div>
                                                1. Sales Invoice Report → Filters by Payment Date<br/>
                                                2. Customers Report → Filters by E-Invoice Requested Date<br/>
                                                3. 01D - Sales Deposit Received [AR DEPOSIT ENTRY] → Filters by Payment Date<br/>
                                                4. 01R - RECEIVE PAYMENT [AR RECEIVE PAYMENT] → Filters by Payment Date<br/>
                                                5. Credit Note Report → Filters by Credit Note Created Date<br/>
                                                6. 01DRW - Sales Deposit by Wallet [AR PAYMENT ENTRY] → Filters by Created Date<br/>
                                                7. 01DRF - Sales Deposit by Wallet [AR REFUND ENTRY] → Filters by Created Date<br/>
                                                8. 01DD - Sales Deposit by Wallet [AR DEPOSIT ENTRY] → Filters by Created Date<br/>
                                                9. WALLET TOP UP REPORT [Wallet Deposit Received] → Filters by Top Up Date<br/>
                                            </div>
                                        ">
                                        <i class="fa fa-info-circle"></i>
                                    </span>
                                </label>
                                <date-picker-component :parameters="parameters" v-model.lazy="parameters.endDate"></date-picker-component>
                            </validation-wrapper-component>
                        </div>
                        <div class="col-12 col-md mb-2 mb-md-0 p-l-3 p-r-3 p-md-0">
                            <validation-wrapper-component selectable :validator="v$.parameters.reportType">
                                <label class="all-caps">Report Type</label>
                                <select-component :options="reportTypeOptions" v-model="parameters.reportType"></select-component>
                            </validation-wrapper-component>
                        </div>
                        <div class="col-12 col-md-auto">
                            <div class="btn btn-lg btn-primary fs-11 w-100 h-100 d-flex justify-content-center align-items-center" :class="{ disabled: isDownloading }" @click="handleExportClick">
                                <span>Export</span>
                                <span v-if="isDownloading" class="spinner"></span>
                            </div>
                        </div>
                        <div class="col-12 col-md-auto pl-md-0">
                            <button
                                class="btn btn-lg fs-11 w-100 h-100 d-flex justify-content-center align-items-center"
                                :class="allowedReportTypes.includes(parameters.reportType)
                                            ? 'btn-primary requestModal pointer'
                                            : 'btn-secondary'"
                                :disabled="!allowedReportTypes.includes(parameters.reportType)"
                                :data-type="allowedReportTypes.includes(parameters.reportType)
                                                ? 'uploadDocumentModel'
                                                : null"
                            >
                                <span>Import</span>
                            </button>
                            <modal-component type="uploadDocumentModel">
                                <upload-component :url="importUrl" @importSuccess="importSuccess($event)" :section="section" :report-type="parameters.reportType"></upload-component>
                            </modal-component>
                        </div>
                        <div class="col-12 col-md-auto p-md-0">
                           <button
                                class="btn btn-lg fs-11 w-100 h-100 d-flex justify-content-center align-items-center"
                                :class="parameters.reportType === 'Sales Invoice Report' ? 'btn-primary' : 'btn-secondary'"
                                :disabled="parameters.reportType !== 'Sales Invoice Report'"
                                @click="() => { if (parameters.reportType === 'Sales Invoice Report') handleGenerateEInvoiceClick() }"
                            >
                                <span>Process E-Invoices</span>
                            </button>
                            <modal-component
                                class="animate__animated animate__fast animate__fadeIn"
                                styleType="fill-in" size="large"
                                id="modal-generate-einvoice">
                                <general-confirmation-form-component
                                    contentText="Are you sure you want to batch process for E-Invoices? (Only applicable for bookings with DocNo)"
                                    modalType="confirm"
                                    class="text-center bg-white padding-40 b-rad-lg"
                                    :apiRoute="generateEInvoicesUrl!"
                                    apiMethod="get"
                                    :section="section"
                                    v-if="generateEInvoicesUrl"
                                >
                                </general-confirmation-form-component>
                            </modal-component>
                        </div>
                    </div>
                    <div class="row m-r-0 m-l-0 text-muted small">
                        <em>Note: Date filter not applicable to import</em>
                    </div>
                    <div class="row m-r-0 m-l-0" v-if="error">
                        <small class="bold fs-10 text-danger">{{error}}</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

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

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

const error = ref('');
const parameters = ref({
    startDate: '',
    endDate: '',
    reportType: '',
});
const isDownloading = ref(false);
const generateEInvoicesUrl = ref<string | null>(null);
const allowedReportTypes = [
    'Sales Invoice Report',
    '01R - RECEIVE PAYMENT [AR RECEIVE PAYMENT]',
    'Credit Note Report',
    '01DRW - Sales Deposit by Wallet [AR PAYMENT ENTRY]',
    '01DRF - Sales Deposit by Wallet [AR REFUND ENTRY]',
];

const rules = {
    parameters: {
        startDate: { required },
        endDate: { required },
        reportType: { required },
    }
};

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

const importUrl = computed(() => {
    const reportType = parameters.value.reportType;
    const importRoutesMap: Record<string, string> = {
        'Sales Invoice Report': route('api.import.sales_invoices'),
        '01R - RECEIVE PAYMENT [AR RECEIVE PAYMENT]': route('api.import.official_receipt'),
        'Credit Note Report': route('api.import.credit_note'),
        '01DRW - Sales Deposit by Wallet [AR PAYMENT ENTRY]': route('api.import.sales_deposit'),
        '01DRF - Sales Deposit by Wallet [AR REFUND ENTRY]': route('api.import.sales_deposit'),
    };
    return importRoutesMap[reportType] || '';
});

const reportTypeOptions = computed(() => [
    { id: 'Sales Invoice Report', text: 'Sales Invoice Report' },
    { id: 'Sales Invoice Report (with refund)', text: 'Sales Invoice Report (with refund)' },
    { id: 'Customers Report', text: 'Customers Report' },
    { id: '01D - Sales Deposit Received [AR DEPOSIT ENTRY]', text: '01D - Sales Deposit Received [AR DEPOSIT ENTRY]' },
    { id: '01R - RECEIVE PAYMENT [AR RECEIVE PAYMENT]', text: '01R - RECEIVE PAYMENT [AR RECEIVE PAYMENT]' },
    { id: 'Credit Note Report', text: 'Credit Note Report' },
    { id: '01DRW - Sales Deposit by Wallet [AR PAYMENT ENTRY]', text: '01DRW - Sales Deposit by Wallet [AR PAYMENT ENTRY]' },
    { id: '01DRF - Sales Deposit by Wallet [AR REFUND ENTRY]', text: '01DRF - Sales Deposit by Wallet [AR REFUND ENTRY]' },
    { id: '01DD - Sales Deposit by Wallet [AR DEPOSIT ENTRY]', text: '01DD - Sales Deposit by Wallet [AR DEPOSIT ENTRY]' },
    { id: 'WALLET TOP UP REPORT [Wallet Deposit Received]', text: 'WALLET TOP UP REPORT [Wallet Deposit Received]' },
]);

const successHandler = (response: any) => {
    if (window.LARAVEL_VAPOR_ENABLED) {
        if (response.payload !== undefined && response.payload.src) {
            window.open(response.payload.src, '_blank');
        } else if (response.src) {
            window.open(response.src, '_blank');
        }
    }
    isDownloading.value = false;
};

const errorHandler = (err: any) => {
    isDownloading.value = false;
    error.value = (err.message || 'Error') + '. Please try again with a shorter date span between the two date filters.';
};

const handleExportClick = async () => {
    error.value = '';
    const isFormCorrect = await v$.value.parameters.$validate();
    if (!isFormCorrect) return;

    const reportType = parameters.value.reportType;
    const routesMap: Record<string, string> = {
        'Sales Invoice Report': route('api.export.bookings.sales_invoices'),
        'Sales Invoice Report (with refund)': route('api.export.bookings.sales_invoices_w_refund'),
        'Customers Report': route('api.export.companies.customers_data'),
        '01D - Sales Deposit Received [AR DEPOSIT ENTRY]': route('api.export.transactions.receive_payment_deposit_entry'),
        '01R - RECEIVE PAYMENT [AR RECEIVE PAYMENT]': route('api.export.transactions.receive_payment_for_booking'),
        'Credit Note Report': route('api.export.transactions.ar_credit_note'),
        '01DRW - Sales Deposit by Wallet [AR PAYMENT ENTRY]': route('api.export.transactions.sales_deposit_by_wallet_payment_entry'),
        '01DRF - Sales Deposit by Wallet [AR REFUND ENTRY]': route('api.export.transactions.sales_deposit_by_wallet_refund_entry'),
        '01DD - Sales Deposit by Wallet [AR DEPOSIT ENTRY]': route('api.export.transactions.sales_deposit_by_wallet_deposit_entry'),
        'WALLET TOP UP REPORT [Wallet Deposit Received]': route('api.export.transactions.wallet_top_up_deposit_entry'),
    };

    const url = `${routesMap[reportType]}?startDate=${parameters.value.startDate}&endDate=${parameters.value.endDate}`;
    isDownloading.value = true;

    if (window.LARAVEL_VAPOR_ENABLED) {
        submit(url, 'get', props.section, false, false, undefined, { successHandler, errorHandler });
    } else {
        window.open(url, '_blank');
        isDownloading.value = false;
    }
};

const handleGenerateEInvoiceClick = async () => {
    error.value = '';
    const isFormCorrect = await v$.value.parameters.$validate();
    if (!isFormCorrect) return;

    const reportType = parameters.value.reportType;
    const routesMap: Record<string, string> = {
        'Sales Invoice Report': route('api.booking.batch.process'),
    };

    const selectedRoute = routesMap[reportType];
    if (!selectedRoute) {
        throw new Error(`No route mapping found for report type: ${reportType}`);
    }

    generateEInvoicesUrl.value = `${selectedRoute}?startDate=${parameters.value.startDate}&endDate=${parameters.value.endDate}`;

    // Using jQuery for now as per original
    (window as any).$('#modal-generate-einvoice').modal('show');
};

const importSuccess = (payload: any) => {
    error.value = payload.message + (payload.data || '');
};
</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>

<style>
    .tooltip-report-export .tooltip-inner {
        white-space: nowrap;
        max-width: none !important;
        text-align: left;
    }
</style>
