$(async function () {
    "use strict";
    /** #################### -- The base JS part should be on top of all JS files --  #################### **/
    // Language Translator
    let base_url = $('#base_url').val();
    let language_name = $('#language_name').val();
    let language_path = '/resources/lang/' + language_name + '.json';
    let language_file = base_url + language_path;
    let language_key = {};

    async function loadLanguage() {
        try {
            const res = await fetch(language_file);
            language_key = await res.json();
        } catch (err) {
            console.error('Failed to load language file:', err);
        }
    }
    await loadLanguage();
    /** #################### -- The base JS part should be on top of all JS files --  #################### **/

    let gstReportRoute = typeof route !== 'undefined' ? route('report.gst-report', {}, false, typeof Ziggy !== 'undefined' ? Ziggy : null) : '/reports/gst-report';

    function loadReport() {
        let reportType = $('#report_type').val();
        let dateFrom = $('#date_from').val();
        let dateTo = $('#date_to').val();
        let outletId = $('#outlet_id').val();

        $.ajax({
            url: base_url + gstReportRoute,
            type: 'GET',
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
            data: { report_type: reportType, date_from: dateFrom, date_to: dateTo, outlet_id: outletId },
            success: function (res) {
                if (res.success && res.data) {
                    renderReport(res.report_type, res.data, res.filter_info);
                }
            }
        });
    }

    // Update filtered information header (Report heading, Generated on, Generated by - like attendance-report)
    function updateFilteredInformation(filterInfo, reportTitle) {
        if (!filterInfo) {
            $('#filterInfoContent').html('');
            return;
        }
        let html = `<p class="pb-0 mb-0"><strong>${reportTitle || language_key.GSTReport || 'GST Report'}</strong></p>`;

        if (filterInfo.outlet && filterInfo.outlet.name) {
            html += `<p class="pb-0 mb-0"><strong>${language_key.Outlet || 'Outlet'}: </strong> ${filterInfo.outlet.name}</p>`;
        }

        if (filterInfo.date_from || filterInfo.date_to) {
            let dateRange = `${filterInfo.date_from || ''} to ${filterInfo.date_to || ''}`;
            html += `<p class="pb-0 mb-0"><strong>${language_key.DateRange || 'Date Range'}: </strong> ${dateRange}</p>`;
        }

        if (filterInfo.generated_at) {
            html += `<p class="pb-0 mb-0"><strong>${language_key.GeneratedOn || 'Generated on'}: </strong> ${filterInfo.generated_at}</p>`;
        }
        if (filterInfo.generated_by && (filterInfo.generated_by.name || filterInfo.generated_by.phone)) {
            let byText = [filterInfo.generated_by.name, filterInfo.generated_by.phone].filter(Boolean).join(', ');
            html += `<p class="pb-0 mb-0"><strong>${language_key.GeneratedBy || 'Generated by'}: </strong> ${byText}</p>`;
        }

        $('#filterInfoContent').html(html);
    }

    function renderReport(type, data, filterInfo) {
        let reportTitles = {
            'tax-summary': language_key.GSTTaxSummaryReport || 'GST Tax Summary Report',
            'monthly-summary': language_key.GSTTaxSummaryMonthlyDateWise || 'GST Tax Summary (Monthly/Date Wise)',
            'rate-wise': language_key.GSTRateWiseSummaryReport || 'GST Rate Wise Summary Report',
            'b2b': language_key.B2BReportGSTR1 || 'B2B Report (GSTR-1)',
            'b2c-small': language_key.B2CSmallStateWise || 'B2C Small (State Wise)',
            'b2c-large': language_key.B2CLargeInterstate || 'B2C Large (Interstate >2.5L)',
            'hsn-summary': language_key.HSNSummaryReport || 'HSN Summary Report',
            'gstr3b': language_key.GSTR3BSummary || 'GSTR-3B Summary'
        };
        let reportTitle = reportTitles[type] || language_key.GSTReport || 'GST Report';
        $('#reportTitle').text(reportTitle);
        updateFilteredInformation(filterInfo, reportTitle);

        let html = '';
        const TaxType = language_key.TaxType || 'Tax Type';
        const TaxableValue = language_key.TaxableValue || 'Taxable Value';
        const CGST = language_key.CGST || 'CGST';
        const SGST = language_key.SGST || 'SGST';
        const IGST = language_key.IGST || 'IGST';
        const TotalTax = language_key.TotalTax || 'Total Tax';
        const InvoiceCount = language_key.InvoiceCount || 'Invoice Count';
        const Total = language_key.Total || 'Total';
        const Particular = language_key.Particular || 'Particular';
        const Amount = language_key.Amount || 'Amount';
        const GSTPercent = language_key.GSTPercent || 'GST %';
        const InvoiceNo = language_key.InvoiceNo || 'Invoice No';
        const Date = language_key.Date || 'Date';
        const Customer = language_key.Customer || 'Customer';
        const GSTIN = language_key.GSTIN || 'GSTIN';
        const State = language_key.State || 'State';
        const TotalInvoiceValue = language_key.TotalInvoiceValue || 'Total Invoice Value';
        const HSNCode = language_key.HSNCode || 'HSN Code';
        const TotalQuantity = language_key.TotalQuantity || 'Total Quantity';
        const NatureOfSupply = language_key.NatureOfSupply || 'Nature of Supply';
        const TotalTaxCGSTSGSTIGST = language_key.TotalTaxCGSTSGSTIGST || 'Total Tax (CGST+SGST+IGST)';
        const NoData = language_key.NoData || 'No data';

        switch (type) {
            case 'tax-summary':
                html = `<table class="table table-bordered"><thead><tr><th>${TaxType}</th><th class="text-end">${TaxableValue}</th><th class="text-end">${CGST}</th><th class="text-end">${SGST}</th><th class="text-end">${IGST}</th><th class="text-end">${TotalTax}</th><th class="text-center">${InvoiceCount}</th></tr></thead><tbody>`;
                (data.rows || []).forEach(function (r) {
                    html += `<tr><td>${r.tax_type || ''}</td><td class="text-end">${r.taxable_value}</td><td class="text-end">${r.cgst}</td><td class="text-end">${r.sgst}</td><td class="text-end">${r.igst}</td><td class="text-end">${r.total_tax}</td><td class="text-center">${r.invoice_count || 0}</td></tr>`;
                });
                if (data.totals) {
                    html += `<tr class="fw-bold"><td>${Total}</td><td class="text-end">${data.totals.taxable_value}</td><td class="text-end">${data.totals.cgst}</td><td class="text-end">${data.totals.sgst}</td><td class="text-end">${data.totals.igst}</td><td class="text-end">${data.totals.total_tax}</td><td class="text-center">${data.totals.invoice_count || 0}</td></tr>`;
                }
                html += '</tbody></table>';
                break;

            case 'monthly-summary':
                html = `<table class="table table-bordered"><thead><tr><th>${Particular}</th><th class="text-end">${Amount}</th></tr></thead><tbody>`;
                (data.particulars || []).forEach(function (p) {
                    html += `<tr><td>${p.label || ''}</td><td class="text-end">${p.amount}</td></tr>`;
                });
                html += '</tbody></table>';
                break;

            case 'rate-wise':
                html = `<table class="table table-bordered"><thead><tr><th>${GSTPercent}</th><th class="text-end">${TaxableValue}</th><th class="text-end">${CGST}</th><th class="text-end">${SGST}</th><th class="text-end">${IGST}</th><th class="text-end">${TotalTax}</th></tr></thead><tbody>`;
                (data.rows || []).forEach(function (r) {
                    html += `<tr><td>${r.gst_percent || ''}</td><td class="text-end">${r.taxable_value}</td><td class="text-end">${r.cgst}</td><td class="text-end">${r.sgst}</td><td class="text-end">${r.igst}</td><td class="text-end">${r.total_tax}</td></tr>`;
                });
                if (data.totals) {
                    html += `<tr class="fw-bold"><td>${Total}</td><td class="text-end">${data.totals.taxable_value}</td><td class="text-end">${data.totals.cgst}</td><td class="text-end">${data.totals.sgst}</td><td class="text-end">${data.totals.igst}</td><td class="text-end">${data.totals.total_tax}</td></tr>`;
                }
                html += '</tbody></table>';
                break;

            case 'b2b':
                html = `<table class="table table-bordered table-sm"><thead><tr><th>${InvoiceNo}</th><th>${Date}</th><th>${Customer}</th><th>${GSTIN}</th><th>${State}</th><th class="text-end">${TaxableValue}</th><th class="text-end">${CGST}</th><th class="text-end">${SGST}</th><th class="text-end">${IGST}</th><th class="text-end">${TotalInvoiceValue}</th></tr></thead><tbody>`;
                (data.rows || []).forEach(function (r) {
                    html += `<tr><td>${r.invoice_no || ''}</td><td>${r.invoice_date || ''}</td><td>${r.customer_name || ''}</td><td>${r.gstin || ''}</td><td>${r.state_code || ''}</td><td class="text-end">${r.taxable_value}</td><td class="text-end">${r.cgst}</td><td class="text-end">${r.sgst}</td><td class="text-end">${r.igst}</td><td class="text-end">${r.total_invoice_value}</td></tr>`;
                });
                if (data.totals) {
                    html += `<tr class="fw-bold"><td colspan="5">${Total}</td><td class="text-end">${data.totals.taxable_value}</td><td class="text-end">${data.totals.cgst}</td><td class="text-end">${data.totals.sgst}</td><td class="text-end">${data.totals.igst}</td><td class="text-end">${data.totals.total_invoice_value}</td></tr>`;
                }
                html += '</tbody></table>';
                break;

            case 'b2c-small':
                html = `<table class="table table-bordered"><thead><tr><th>${InvoiceNo}</th><th>${Date}</th><th>${State}</th><th>${GSTPercent}</th><th class="text-end">${TaxableValue}</th><th class="text-end">${CGST}</th><th class="text-end">${SGST}</th><th class="text-end">${IGST}</th><th class="text-end">${Total}</th></tr></thead><tbody>`;
                (data.rows || []).forEach(function (r) {
                    html += `<tr><td>${r.invoice_no || ''}</td><td>${r.date || ''}</td><td>${r.state || ''}</td><td>${r.gst_percent || ''}</td><td class="text-end">${r.taxable_value}</td><td class="text-end">${r.cgst}</td><td class="text-end">${r.sgst}</td><td class="text-end">${r.igst}</td><td class="text-end">${r.total}</td></tr>`;
                });
                if (data.totals) {
                    html += `<tr class="fw-bold"><td colspan="4">${Total}</td><td class="text-end">${data.totals.taxable_value}</td><td class="text-end">${data.totals.cgst}</td><td class="text-end">${data.totals.sgst}</td><td class="text-end">${data.totals.igst}</td><td class="text-end">${data.totals.total}</td></tr>`;
                }
                html += '</tbody></table>';
                break;

            case 'b2c-large':
                html = `<table class="table table-bordered"><thead><tr><th>${InvoiceNo}</th><th class="text-end">${TaxableValue}</th><th class="text-end">${TotalInvoiceValue}</th></tr></thead><tbody>`;
                (data.rows || []).forEach(function (r) {
                    html += `<tr><td>${r.invoice_no || ''}</td><td class="text-end">${r.taxable_value}</td><td class="text-end">${r.total_invoice_value}</td></tr>`;
                });
                if (data.totals) {
                    html += `<tr class="fw-bold"><td>${Total}</td><td class="text-end">${data.totals.taxable_value}</td><td class="text-end">${data.totals.total_invoice_value}</td></tr>`;
                }
                html += '</tbody></table>';
                break;

            case 'hsn-summary':
                html = `<table class="table table-bordered"><thead><tr><th>${HSNCode}</th><th class="text-end">${TotalQuantity}</th><th class="text-end">${TaxableValue}</th></tr></thead><tbody>`;
                (data.rows || []).forEach(function (r) {
                    html += `<tr><td>${r.hsn_code || ''}</td><td class="text-end">${r.total_qty} PCS</td><td class="text-end">${r.taxable_value}</td></tr>`;
                });
                if (data.totals) {
                    html += `<tr class="fw-bold"><td>${Total}</td><td class="text-end">${data.totals.total_qty} Units</td><td class="text-end">${data.totals.taxable_value}</td></tr>`;
                }
                html += '</tbody></table>';
                break;

            case 'gstr3b':
                html = `<table class="table table-bordered"><thead><tr><th>${NatureOfSupply}</th><th class="text-end">${TaxableValue}</th><th class="text-end">${TotalTaxCGSTSGSTIGST}</th></tr></thead><tbody>`;
                (data.rows || []).forEach(function (r) {
                    html += `<tr><td>${r.nature || ''}</td><td class="text-end">${r.taxable_value}</td><td class="text-end">${r.total_tax}</td></tr>`;
                });
                if (data.totals) {
                    html += `<tr class="fw-bold"><td>${Total}</td><td class="text-end">${data.totals.taxable_value}</td><td class="text-end">${data.totals.total_tax}</td></tr>`;
                }
                html += '</tbody></table>';
                break;

            default:
                html = `<p class="text-muted">${NoData}</p>`;
        }

        $('#gstReportContent').html(html);
    }

    $('#applyFilter').on('click', loadReport);
    $('#report_type').on('change', function () {
        let reportTitles = {
            'tax-summary': language_key.GSTTaxSummaryReport || 'GST Tax Summary Report',
            'monthly-summary': language_key.GSTTaxSummaryMonthlyDateWise || 'GST Tax Summary (Monthly/Date Wise)',
            'rate-wise': language_key.GSTRateWiseSummaryReport || 'GST Rate Wise Summary Report',
            'b2b': language_key.B2BReportGSTR1 || 'B2B Report (GSTR-1)',
            'b2c-small': language_key.B2CSmallStateWise || 'B2C Small (State Wise)',
            'b2c-large': language_key.B2CLargeInterstate || 'B2C Large (Interstate >2.5L)',
            'hsn-summary': language_key.HSNSummaryReport || 'HSN Summary Report',
            'gstr3b': language_key.GSTR3BSummary || 'GSTR-3B Summary'
        };
        $('#reportTitle').text(reportTitles[$(this).val()] || language_key.GSTReport || 'GST Report');
    });

    if ($('.datePicker').length && $.fn.datepicker) {
        $('.datePicker').datepicker({ format: 'yyyy-mm-dd', autoclose: true });
    }
    if ($('#outlet_id').length && $.fn.select2) {
        $('#outlet_id').select2({ width: '100%', placeholder: language_key.AllOutlets || 'All Outlets' });
    }
});
