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

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

function createInsuranceTable(data) {
    var oInsuranceScrollContainer = new sap.m.ScrollContainer({
        horizontal: true,
        vertical: true,
        width: "100%",
        height: "calc(100vh - 100px)",
        content: []
    }).addStyleClass("insuranceScrollContainer");

    var columns = [
        new sap.m.Column({
            width: "300px",
            minScreenWidth: "30px",
            demandPopin: true,
            header: new sap.m.Text({ 
                text: "Branch",
                wrapping: false 
            }).addStyleClass("insHeaderText")
        })
    ];

    // Add columns for each city with minimum width
    data.forEach(cityData => {
        columns.push(
            new sap.m.Column({
                width: "200px",
                minScreenWidth: "30px",
                demandPopin: true,
                header: new sap.m.Text({ 
                    text: cityData.city_name, 
                    textAlign: "Center",
                    wrapping: false 
                }).addStyleClass("insuranceCityHeader")
            }),
                new sap.m.Column({
                width: "200px",
                minScreenWidth: "30px",
                demandPopin: true,
                header: new sap.m.Text({ 
                    text: "", 
                    textAlign: "Center",
                    wrapping: false 
                })
            })
        );
    });

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

    oInsuranceScrollContainer.addContent(oInsuranceTable);

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

    oInsuranceTable.addItem(new sap.m.ColumnListItem({
        cells: vehicleTypeCells
    }).addStyleClass("insVehicleTypeRow"));

    // Helper function to get value or default to "-"
    function getInsValue(cityData, key) {
        return cityData[key] || "-";
    }

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

    // Helper function to add rows
    function addInsuranceRow(label, heavyAKey, lightAKey, styleClass = "", isSubItem = false, isItalic = false) {
        var cells = [new sap.m.Text({ 
            text: isSubItem ? "    " + label : label,
            wrapping: true 
        }).addStyleClass(isSubItem ? "insSubItem" : "")
          .addStyleClass(isItalic ? "insItalicText" : "")];
        
        data.forEach(cityData => {
            let heavyAValue = "-";
            let lightAValue = "-";

            switch(label) {
                case "Not Active Car":
                    // Calculate sum for Not Active Car
                    const notActiveHeavySum = getNumericValue(cityData, "not_active_tlo_heavy_a") +
                                           getNumericValue(cityData, "not_active_tla_heavy_a") +
                                           getNumericValue(cityData, "not_active_writeoff_heavy_a");
                    
                    const notActiveLightSum = getNumericValue(cityData, "not_active_tlo_lite_a") +
                                           getNumericValue(cityData, "not_active_tla_lite_a") +
                                           getNumericValue(cityData, "not_active_writeoff_lite_a");
                    
                    heavyAValue = notActiveHeavySum > 0 ? notActiveHeavySum.toString() : "-";
                    lightAValue = notActiveLightSum > 0 ? notActiveLightSum.toString() : "-";
                    break;

                case "Past Due Expired":
                    // Calculate sum for Past Due Expired
                    const pastDueHeavySum = 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");
                    
                    const pastDueLightSum = 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");
                    
                    heavyAValue = pastDueHeavySum > 0 ? pastDueHeavySum.toString() : "-";
                    lightAValue = pastDueLightSum > 0 ? pastDueLightSum.toString() : "-";
                    break;

                case "Below & 3 Month Approaching Expired":
                    // Calculate sum for Below & 3 Month Approaching Expired
                    const approachingHeavySum = getNumericValue(cityData, "approaching_1_month_heavy_a") +
                                              getNumericValue(cityData, "approaching_2_month_heavy_a") +
                                              getNumericValue(cityData, "approaching_3_month_heavy_a");
                    
                    const approachingLightSum = getNumericValue(cityData, "approaching_1_month_lite_a") +
                                              getNumericValue(cityData, "approaching_2_month_lite_a") +
                                              getNumericValue(cityData, "approaching_3_month_lite_a");
                    
                    heavyAValue = approachingHeavySum > 0 ? approachingHeavySum.toString() : "-";
                    lightAValue = approachingLightSum > 0 ? approachingLightSum.toString() : "-";
                    break;

                case "Total Unit Active":
                    // Calculate sum for Total Unit Active
                    const activeHeavySum = 
                        // Past Due components
                        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") +
                        // Approaching Expired components
                        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");
                    
                    const activeLightSum = 
                        // Past Due components
                        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") +
                        // Approaching Expired components
                        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");
                    
                    heavyAValue = activeHeavySum > 0 ? activeHeavySum.toString() : "-";
                    lightAValue = activeLightSum > 0 ? activeLightSum.toString() : "-";
                    break;

                case "Total Unit Plan Disposal":
                    // Calculate sum for Total Unit Plan Disposal
                    const disposalHeavySum = 
                        // Past Due Expired
                        getNumericValue(cityData, "past_expired_disposal_heavy_a") +
                        // Below & 3 Month Approaching Expired
                        getNumericValue(cityData, "approaching_expiry_below_3_months_disposal_heavy_a") +
                        // Above 3 Month Approaching Expired
                        getNumericValue(cityData, "approaching_expiry_above_3_months_disposal_heavy_a");
                    
                    const disposalLightSum = 
                        // Past Due Expired
                        getNumericValue(cityData, "past_expired_disposal_lite_a") +
                        // Below & 3 Month Approaching Expired
                        getNumericValue(cityData, "approaching_expiry_below_3_months_disposal_lite_a") +
                        // Above 3 Month Approaching Expired
                        getNumericValue(cityData, "approaching_expiry_above_3_months_disposal_lite_a");
                    
                    heavyAValue = disposalHeavySum > 0 ? disposalHeavySum.toString() : "-";
                    lightAValue = disposalLightSum > 0 ? disposalLightSum.toString() : "-";
                    break;

                case "Total No Active Insurance":
                    // Calculate sum for Total No Active Insurance
                    const noInsuranceHeavySum = 
                        // Unit Active
                        getNumericValue(cityData, "missing_docs_active_heavy_a") +
                        // Plan Disposal
                        getNumericValue(cityData, "missing_docs_pending_disposal_heavy_a");
                    
                    const noInsuranceLightSum = 
                        // Unit Active
                        getNumericValue(cityData, "missing_docs_active_lite_a") +
                        // Plan Disposal
                        getNumericValue(cityData, "missing_docs_pending_disposal_lite_a");
                    
                    heavyAValue = noInsuranceHeavySum > 0 ? noInsuranceHeavySum.toString() : "-";
                    lightAValue = noInsuranceLightSum > 0 ? noInsuranceLightSum.toString() : "-";
                    break;

                default:
                    heavyAValue = getInsValue(cityData, heavyAKey);
                    lightAValue = getInsValue(cityData, lightAKey);
            }

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

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

    // Add rows exactly as in the image
    addInsuranceRow("Grand total", "total_units", "total_units", "insTotalRow");
    addInsuranceRow("Vehicle category", "total_heavy_a", "total_lite_a", "insVehicleOwnRow");
    
    // Not Active Car section
    addInsuranceRow("Not Active Car", "", "", "insNotActiveRow");
    addInsuranceRow("TLO", "not_active_tlo_heavy_a", "not_active_tlo_lite_a", "insSubRow", true);
    addInsuranceRow("TLA", "not_active_tla_heavy_a", "not_active_tla_lite_a", "insSubRow", true);
    addInsuranceRow("Writeoff", "not_active_writeoff_heavy_a", "not_active_writeoff_lite_a", "insSubRow", true);

    // Not Active Car With Insurance still Active
    addInsuranceRow("Not Active Car With Insurance still Active", "", "", "insNotActiveInsRow insHeaderBold");
    addInsuranceRow("Past Due Expired", "past_expired_inactive_heavy_a", "past_expired_inactive_lite_a", "insPastDueRow", true);
    addInsuranceRow("Below & 3 Month Approaching Expired", "approaching_expiry_below_3_months_inactive_heavy_a", "approaching_expiry_below_3_months_inactive_lite_a", "insSubRow", true);
    addInsuranceRow("Above 3 Month Approaching Expired", "approaching_expiry_above_3_months_inactive_heavy_a", "approaching_expiry_above_3_months_inactive_lite_a", "insSubRow", true);
    addInsuranceRow("Total Unit Not Active with Insurance still Active", "", "", "insTotalUnitRow");

    // Active Car section with updated styling
    addInsuranceRow("Active Car", "", "", "insActiveCarRow");
    addInsuranceRow("Past Due Expired", "", "", "insSubRow insPastDueHeader", true);
    addInsuranceRow("Past 1 Month", "past_1_month_heavy_a", "past_1_month_lite_a", "insSubRow", true, true);
    addInsuranceRow("Past 2 Month", "past_2_month_heavy_a", "past_2_month_lite_a", "insSubRow", true, true);
    addInsuranceRow("Past 3 Month", "past_3_month_heavy_a", "past_3_month_lite_a", "insSubRow", true, true);
    addInsuranceRow("Above Past 3 Month", "past_above_3_month_heavy_a", "past_above_3_month_lite_a", "insSubRow", true, true);
    
    addInsuranceRow("Below & 3 Month Approaching Expired", "", "", "insSubRow insApproachingHeader", true);
    addInsuranceRow("1 Month Approaching Expired", "approaching_1_month_heavy_a", "approaching_1_month_lite_a", "insSubRow", true, true);
    addInsuranceRow("2 Month Approaching Expired", "approaching_2_month_heavy_a", "approaching_2_month_lite_a", "insSubRow", true, true);
    addInsuranceRow("3 Month Approaching Expired", "approaching_3_month_heavy_a", "approaching_3_month_lite_a", "insSubRow", true, true);
    
    addInsuranceRow("Above 3 Month Approaching Expired", "approaching_above_3_month_heavy_a", "approaching_above_3_month_lite_a", "insSubRow insApproachingHeader", true);
    addInsuranceRow("Total Unit Active", "", "", "insTotalUnitRow");

    // Plan Disposal + Sold section with calculated total
    addInsuranceRow("Plan Disposal + Sold", "", "", "insPlanDisposalRow");
    addInsuranceRow("Past Due Expired", "past_expired_disposal_heavy_a", "past_expired_disposal_lite_a", "insSubRow redText", true);
    addInsuranceRow("Below & 3 Month Approaching Expired", "approaching_expiry_below_3_months_disposal_heavy_a", "approaching_expiry_below_3_months_disposal_lite_a", "insSubRow", true);
    addInsuranceRow("Above 3 Month Approaching Expired", "approaching_expiry_above_3_months_disposal_heavy_a", "approaching_expiry_above_3_months_disposal_lite_a", "insSubRow", true);
    addInsuranceRow("Total Unit Plan Disposal", "", "", "insTotalUnitRow");

    // No Active Insurance section with calculated total
    addInsuranceRow("No Active Insurance", "", "", "insNoActiveInsRow");
    addInsuranceRow("Unit Active", "missing_docs_active_heavy_a", "missing_docs_active_lite_a", "insSubRow", true, true);
    addInsuranceRow("Plan Disposal", "missing_docs_pending_disposal_heavy_a", "missing_docs_pending_disposal_lite_a", "insSubRow", true, true);
    addInsuranceRow("Total No Active Insurance", "", "", "insTotalUnitRow");

    // Add CSS styles
    var style = document.createElement('style');
    style.textContent = `
        .insuranceScrollContainer {
            margin: 0;
            border: 1px solid #e5e5e5;
            height: 100% !important;
        }
        .insuranceTable {
            margin: 0;
            width: 100%;
        }
        .insuranceCityHeader {
            font-size: 1.2rem !important;
            font-weight: bold !important;
            background-color: #87CEEB !important;
            text-align: center !important;
        }
        .insVehicleTypeRow {
            background-color: #FFFFFF !important;
        }
        .insVehicleTypeText {
            font-weight: bold !important;
            text-align: center !important;
        }
        .insTotalRow {
            background-color: #FFFFFF !important;
            font-weight: bold;
        }
        .insVehicleOwnRow {
            background-color: #FFFFFF !important;
        }
        .insSubRow {
            background-color: #FFFFFF !important;
        }
        .insNotActiveRow, .insActiveCarRow {
            background-color: #FFFFFF !important;
            font-weight: bold;
        }
        .insPlanDisposalRow {
            background-color: #90EE90 !important;
            font-weight: bold;
        }
        .insNoActiveInsRow {
            background-color: #FFE4B5 !important;
            font-weight: bold;
        }
        .insSubItem {
            padding-left: 2rem !important;
        }
        .insItalicText {
            font-style: italic !important;
        }
        .insPastDueRow {
            color: #FF0000 !important;
        }
        .redText {
            color: #FF0000 !important;
        }
        .insTotalUnitRow {
            font-weight: bold;
            border-top: 1px solid #000000;
        }
        .insHeaderBold {
            font-weight: bold !important;
            background-color: #FFFFFF !important;
        }
        .insuranceTable .sapMListTbl td,
        .insuranceTable .sapMListTbl th {
            min-width: 30px !important;
            padding: 0.5rem !important;
        }
        
        .insuranceTable .sapMListTbl {
            table-layout: fixed;
            width: 100%;
            min-width: max-content; /* Ensure table expands to fit all columns */
        }

        .insHeaderText {
            font-weight: bold !important;
            white-space: nowrap !important;
        }

        .insPastDueHeader {
            font-weight: bold !important;
            color: #FF0000 !important;
        }

        .insApproachingHeader {
            font-weight: bold !important;
        }
    `;
    document.head.appendChild(style);

    return oInsuranceScrollContainer;
}

function loadInsuranceData() {
    oVehicleInsurenceDashboardPageLayout.setBusy(true);

    $.ajax({
        url: `${jrs_go_api_url_name}/vehicle/insurance/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("Insurance API Response:", response.data);
                
                const sortedData = response.data.sort((a, b) => 
                    (a.city_name || "").localeCompare(b.city_name || "")
                );
                
                var oInsuranceTable = createInsuranceTable(sortedData);
                
                var oInsuranceSection = new sap.uxap.ObjectPageSection({
                    showTitle: false,
                    subSections: [
                        new sap.uxap.ObjectPageSubSection({
                            blocks: [oInsuranceTable]
                        })
                    ]
                });

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

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

    oVehicleInsurenceDashboardPageLayout.addSection(oMainSection);

    // Load dashboard data
    loadInsuranceData();
}

function loadVehicleInsurenceDashboard() {
    try {
        initVehicleInsurenceDashboard();
    } catch (error) {
        console.error("Error initializing insurance dashboard:", error);
    }
    return {};
}

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