// Vehicle Renewable Dashboard Page Layout
var oVehicleRenewableDashboardPageLayout = new sap.uxap.ObjectPageLayout("vehicleRenewableDashboardPageLayout", {
    showTitleInHeaderContent: true,
    showHeaderContent: true,
    showFooter: false,
    headerTitle: new sap.uxap.ObjectPageDynamicHeaderTitle({
        heading: new sap.m.Title({ 
            text: "Vehicle Renewable Dashboard",
            level: "H1",
            wrapping: true
        }).addStyleClass("sapUiTinyMargin")
    }),
    sections: [],
    height: "100%" // Set height to 100%
});

// Create the page
var vehicleRenewableDashboardPage = new sap.m.Page("vehicleRenewableDashboardPage", {
    showHeader: false,
    content: [oVehicleRenewableDashboardPageLayout],
    // height: "100%" // Set height to 100%
});

function createDashboardTable1(data) {
    // Create a container for the table with both horizontal and vertical scroll
    var oScrollContainer = new sap.m.ScrollContainer({
        horizontal: true,
        vertical: true,
        width: "100%",
        height: "calc(100vh - 100px)", // Adjust height to fill screen minus header
        content: []
    }).addStyleClass("dashboardScrollContainer");

    // First, create base column for labels
    var columns = [
        new sap.m.Column({
            width: "300px", // Keep label column width
            minScreenWidth: "30px", // Minimum width
            header: new sap.m.Text({ text: "" })
        })
    ];

    // Dynamically add two columns for each city (Heavy A and Light A)
    data.forEach(cityData => {
        columns.push(
            // Column for Heavy A
            new sap.m.Column({
                width: "200px", // Fixed width for data columns
                minScreenWidth: "30px", // Minimum width
                demandPopin: true, // Enable column popin on small screens
                header: new sap.m.Text({ 
                    text: cityData.city_name, 
                    textAlign: "Center" 
                }).addStyleClass("cityHeader")
            }),
            // Column for Light A
            new sap.m.Column({
                width: "200px", // Fixed width for data columns
                minScreenWidth: "30px", // Minimum width
                demandPopin: true, // Enable column popin on small screens
                header: new sap.m.Text({ text: "", textAlign: "Center" })
            })
        );
    });

    var oTable = new sap.m.Table({
        fixedLayout: true,
        inset: false,
        showSeparators: "All",
        columns: columns
    }).addStyleClass("dashboardTable");

    // Add the table to the scroll container
    oScrollContainer.addContent(oTable);

    // Create vehicle type row cells
    var vehicleTypeCells = [new sap.m.Text({ text: "" })];
    data.forEach(() => {
        vehicleTypeCells.push(
            new sap.m.Text({ text: "Heavy A" }).addStyleClass("vehicleTypeText"),
            new sap.m.Text({ text: "Light A" }).addStyleClass("vehicleTypeText")
        );
    });

    // Add vehicle type row
    oTable.addItem(new sap.m.ColumnListItem({
        cells: vehicleTypeCells
    }).addStyleClass("vehicleTypeRow"));

    // Helper function to get value or default to "-"
    function getValue(cityData, key, type) {
        const value = cityData[`${key}_${type}`] || cityData[key];
        return value || "-";
    }

    // Helper function to get numeric value or 0
    function getNumericValue(cityData, key, type) {
        const value = cityData[`${key}_${type}`] || cityData[key] || 0;
        return typeof value === 'number' ? value : 0;
    }

    // Helper function to add rows with calculations
    function addRow(label, dataKey, styleClass = "", isSubItem = false) {
        var cells = [new sap.m.Text({ text: isSubItem ? "    " + label : label })
            .addStyleClass(isSubItem ? "subItem" : "")];
        
        data.forEach(cityData => {
            let heavyAValue = "-";
            let lightAValue = "-";

            switch(label) {
                case "Not Active Car":
                    heavyAValue = getNumericValue(cityData, "not_active_tlo", "heavy_a") +
                                getNumericValue(cityData, "not_active_tla", "heavy_a") +
                                getNumericValue(cityData, "not_active_writeoff", "heavy_a");
                    lightAValue = getNumericValue(cityData, "not_active_tlo", "lite_a") +
                                getNumericValue(cityData, "not_active_tla", "lite_a") +
                                getNumericValue(cityData, "not_active_writeoff", "lite_a");
                    break;

                case "Past Due Expired":
                    heavyAValue = getNumericValue(cityData, "past_1_month", "heavy_a") +
                                getNumericValue(cityData, "past_2_month", "heavy_a") +
                                getNumericValue(cityData, "past_3_month", "heavy_a") +
                                getNumericValue(cityData, "past_above_3_month", "heavy_a");
                    lightAValue = getNumericValue(cityData, "past_1_month", "lite_a") +
                                getNumericValue(cityData, "past_2_month", "lite_a") +
                                getNumericValue(cityData, "past_3_month", "lite_a") +
                                getNumericValue(cityData, "past_above_3_month", "lite_a");
                    break;

                case "Below & 3 Month Approaching Expired":
                    heavyAValue = getNumericValue(cityData, "approaching_1_month", "heavy_a") +
                                getNumericValue(cityData, "approaching_2_month", "heavy_a") +
                                getNumericValue(cityData, "approaching_3_month", "heavy_a");
                    lightAValue = getNumericValue(cityData, "approaching_1_month", "lite_a") +
                                getNumericValue(cityData, "approaching_2_month", "lite_a") +
                                getNumericValue(cityData, "approaching_3_month", "lite_a");
                    break;

                case "Total Unit Active excluding Plan Disposal":
                    heavyAValue = getNumericValue(cityData, "past_1_month", "heavy_a") +
                                getNumericValue(cityData, "past_2_month", "heavy_a") +
                                getNumericValue(cityData, "past_3_month", "heavy_a") +
                                getNumericValue(cityData, "past_above_3_month", "heavy_a") +
                                getNumericValue(cityData, "approaching_1_month", "heavy_a") +
                                getNumericValue(cityData, "approaching_2_month", "heavy_a") +
                                getNumericValue(cityData, "approaching_3_month", "heavy_a") +
                                getNumericValue(cityData, "approaching_above_3_month", "heavy_a");
                    lightAValue = getNumericValue(cityData, "past_1_month", "lite_a") +
                                getNumericValue(cityData, "past_2_month", "lite_a") +
                                getNumericValue(cityData, "past_3_month", "lite_a") +
                                getNumericValue(cityData, "past_above_3_month", "lite_a") +
                                getNumericValue(cityData, "approaching_1_month", "lite_a") +
                                getNumericValue(cityData, "approaching_2_month", "lite_a") +
                                getNumericValue(cityData, "approaching_3_month", "lite_a") +
                                getNumericValue(cityData, "approaching_above_3_month", "lite_a");
                    break;

                case "Total Unit Plan Disposal":
                    // Calculate Past Due Expired for disposal
                    const pastDueDisposal = getNumericValue(cityData, "past_expired_disposal", "heavy_a");
                    // Calculate Below & 3 Month
                    const below3MonthDisposal = getNumericValue(cityData, "approaching_expiry_below_3_months_disposal", "heavy_a");
                    // Get Above 3 Month
                    const above3MonthDisposal = getNumericValue(cityData, "approaching_expiry_above_3_months_disposal", "heavy_a");
                    
                    heavyAValue = pastDueDisposal + below3MonthDisposal + above3MonthDisposal;
                    
                    // Same for Light A
                    const pastDueDisposalLite = getNumericValue(cityData, "past_expired_disposal", "lite_a");
                    const below3MonthDisposalLite = getNumericValue(cityData, "approaching_expiry_below_3_months_disposal", "lite_a");
                    const above3MonthDisposalLite = getNumericValue(cityData, "approaching_expiry_above_3_months_disposal", "lite_a");
                    
                    lightAValue = pastDueDisposalLite + below3MonthDisposalLite + above3MonthDisposalLite;
                    break;

                case "Not Active STNK":
                    heavyAValue = getNumericValue(cityData, "missing_docs_active", "heavy_a") +
                                getNumericValue(cityData, "missing_docs_pending_disposal", "heavy_a");
                    lightAValue = getNumericValue(cityData, "missing_docs_active", "lite_a") +
                                getNumericValue(cityData, "missing_docs_pending_disposal", "lite_a");
                    break;

                default:
                    heavyAValue = getValue(cityData, dataKey, "heavy_a");
                    lightAValue = getValue(cityData, dataKey, "lite_a");
            }

            // Convert to "-" if value is 0
            heavyAValue = heavyAValue === 0 ? "-" : heavyAValue;
            lightAValue = lightAValue === 0 ? "-" : lightAValue;

            cells.push(
                new sap.m.Text({ text: heavyAValue.toString() }),
                new sap.m.Text({ text: lightAValue.toString() })
            );
        });

        oTable.addItem(new sap.m.ColumnListItem({
            cells: cells
        }).addStyleClass(styleClass));
    }

    // Add Total Unit row first
    addRow("Total Unit", "total_units", "totalRow");

    // Add Vehicle Own section
    addRow("Vehicle Own", "total", "vehicleOwnRow");
    addRow("#unit", "total", "subRow", true);

    // Add Not Active Car section
    addRow("Not Active Car", "not_active_total", "notActiveRow");
    addRow("TLO", "not_active_tlo", "subRow", true);
    addRow("TLA", "not_active_tla", "subRow", true);
    addRow("Writeoff", "not_active_writeoff", "subRow", true);

    // Add Active Car section
    addRow("Active Car excluding Plan Disposal", "", "activeCarRow");
    
    // Past Due Expired section
    addRow("Past Due Expired", "past_due_total", "pastDueRow");
    addRow("Past 1 Month", "past_1_month", "subRow", true);
    addRow("Past 2 Month", "past_2_month", "subRow", true);
    addRow("Past 3 Month", "past_3_month", "subRow", true);
    addRow("Above Past 3 Month", "past_above_3_month", "subRow", true);

    // Below & 3 Month Approaching Expired section
    addRow("Below & 3 Month Approaching Expired", "approaching_total", "approachingRow");
    addRow("1 Month Approaching Expired", "approaching_1_month", "subRow", true);
    addRow("2 Month Approaching Expired", "approaching_2_month", "subRow", true);
    addRow("3 Month Approaching Expired", "approaching_3_month", "subRow", true);
    addRow("Above 3 Month Approaching Expired", "approaching_above_3_month", "approachingRow");

    // Total Unit Active excluding Plan Disposal
    addRow("Total Unit Active excluding Plan Disposal", "total_active", "totalActiveRow");

    // Plan Disposal + Sold section
    addRow("Plan Disposal + Sold", "", "planDisposalRow");
    addRow("Past Due Expired", "past_expired_disposal", "subRow redText", true);
    addRow("Below & 3 Month Approaching Expired", "approaching_expiry_below_3_months_disposal", "subRow", true);
    addRow("Above 3 Month Approaching Expired", "approaching_expiry_above_3_months_disposal", "subRow", true);
    addRow("Total Unit Plan Disposal", "total_disposal", "totalActiveRow");

    // Not Active STNK section
    addRow("Not Active STNK", "", "notActiveStnkRow");
    addRow("Unit Active", "missing_docs_active", "subRow", true);
    addRow("Plan Disposal + Sold", "missing_docs_pending_disposal", "subRow", true);

    // Update CSS
    var style = document.createElement('style');
    style.textContent = `
        .dashboardScrollContainer {
            margin: 0;  /* Remove margin */
            border: 1px solid #e5e5e5;
            height: 100% !important;
        }
        .dashboardTable {
            margin: 0;
            width: 100%;
        }
        .dashboardTable .sapMListTbl {
            border-collapse: collapse;
            table-layout: fixed;
            width: 100%;
        }
        .dashboardTable .sapMListTbl td,
        .dashboardTable .sapMListTbl th {
            min-width: 30px !important;
            padding: 0.5rem !important;
        }
        .dashboardTable .sapMListTbl {
            border-collapse: collapse;
            table-layout: fixed;
            width: 100%;
            min-width: max-content; /* Ensure table expands to fit all columns */
        }
        /* Make the ObjectPageLayout take full height */
        #vehicleRenewableDashboardPageLayout {
            height: calc(100vh - 50px) !important;
        }
        /* Make the section container take full height */
        .sapUxAPObjectPageContainer {
            height: 100% !important;
        }
        .sapUxAPBlockContainer {
            padding: 0 !important;
        }
        .sapUxAPObjectPageSubSection {
            padding: 0 !important;
        }
        .cityHeader {
            font-size: 1.2rem !important;
            font-weight: bold !important;
            color: #333333 !important;
            background-color: #E6F2F7 !important;
            text-align: center !important;
            padding: 0.5rem !important;
            white-space: nowrap !important;
            position: sticky !important;
            top: 0 !important;
            z-index: 2 !important;
        }
        .vehicleTypeRow {
            background-color: #FFFFFF !important;
            position: sticky !important;
            top: 43px !important;
            z-index: 2 !important;
        }
        .vehicleTypeText {
            font-weight: bold !important;
            text-align: center !important;
        }
        .totalRow {
            background-color: #E6F2F7 !important;
            font-weight: bold;
        }
        .vehicleOwnRow {
            background-color: #F7F7F7 !important;
            font-weight: bold;
        }
        .notActiveRow, .activeCarRow, .planDisposalRow, .notActiveStnkRow {
            background-color: #E8F8E8 !important;
            font-weight: bold;
        }
        .subRow {
            background-color: #F7F7F7 !important;
        }
        .subItem {
            padding-left: 2rem !important;
            font-style: italic;
        }
        .redText {
            color: #FF0000 !important;
        }
        .pastDueRow {
            color: #FF0000 !important;
            font-weight: bold;
        }
        .approachingRow {
            font-weight: bold;
        }
        .totalActiveRow {
            background-color: #E8F8E8 !important;
            font-weight: bold;
        }
        .sapMText {
            font-size: 0.875rem;
        }
    `;
    document.head.appendChild(style);

    return oScrollContainer;
}

function loadDashboardData() {
    oVehicleRenewableDashboardPageLayout.setBusy(true);

    $.ajax({
        url: `${jrs_go_api_url_name}/vehicle/documents/dashboard?master_email=${emailUser}`,
        method: 'GET',
        headers: {
            'X-API-Key': jrs_go_api_key,
            'accept': 'application/json'
        },
        success: function(response) {
            if (response && response.data) {
                console.log("API Response:", response.data);
                
                // Sort cities alphabetically
                const sortedData = response.data.sort((a, b) => 
                    (a.city_name || "").localeCompare(b.city_name || "")
                );
                
                var oScrollContainer = createDashboardTable1(sortedData);
                
                var oMainSection = new sap.uxap.ObjectPageSection({
                    showTitle: false,
                    subSections: [
                        new sap.uxap.ObjectPageSubSection({
                            blocks: [oScrollContainer]
                        })
                    ]
                });

                oVehicleRenewableDashboardPageLayout.removeAllSections();
                oVehicleRenewableDashboardPageLayout.addSection(oMainSection);
            }
            oVehicleRenewableDashboardPageLayout.setBusy(false);
        },
        error: function(xhr, status, error) {
            console.error("Failed to load dashboard data:", error);
            oVehicleRenewableDashboardPageLayout.setBusy(false);
            sap.m.MessageBox.error("Failed to load dashboard data: " + error);
        }
    });
}

function initVehicleRenewableDashboard() {
    // Empty section to maintain layout structure
    var oMainSection = new sap.uxap.ObjectPageSection({
        showTitle: false,
        subSections: [
            new sap.uxap.ObjectPageSubSection({
                blocks: []
            })
        ]
    });

    oVehicleRenewableDashboardPageLayout.addSection(oMainSection);

    // Load dashboard data
    loadDashboardData();
};

function loadVehicleRenewableDashboard() {
    try {
        initVehicleRenewableDashboard();
    } catch (error) {
        console.error("Error initializing renewable dashboard:", error);
    }
    return {};
}

jQuery(document).ready(function() {
    // try {
        // initVehicleRenewableDashboard();
        
    // } catch (error) {
    //     console.error("Error in document ready:", error);
    // }
});
