
var type = window.dashboardConfig.type;
var userCountry = window.dashboardConfig.userCountry;
var baseUrl = window.dashboardConfig.baseUrl;
var nonce = window.dashboardConfig.nonce;

$(document).ready(function() {
    $('#multiSelect').select2({
        placeholder: "Select countries",
        allowClear: true
    });
});

function country_value_modal_populate(data) {
    const container = document.getElementById('country_finance_value_col');
    container.innerHTML = '';
    data.forEach(item => {
        const isoLowerCase = item.iso.toLowerCase();
        const formattedSum = parseFloat(item.sum_in_usd).toFixed(2);
        const html = `
            <div class="col-md-6">
                <div class="row">
                    <div class="col-md-6">
                        <img src="${baseUrl}assets/img/flags/${isoLowerCase}.png" alt="${item.country_name} Image" class="img-fluid country-flag">
                    </div>
                    <div class="col-md-6">
                        <h3>${item.country_name}</h3>
                        <h5>${item.amount_in_local} ${item.currency_code}</h5>
                    </div>
                </div>
            </div>
        `;
        container.insertAdjacentHTML('beforeend', html);
    });
}

function loadTooltip() {
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl, {
            html: true
        });
    });
}

let projectChart;

function year_chart(yearslabels, yeardataset_start, yeardataset_end, fundsdataset) {
    if (projectChart) {
        projectChart.destroy();
        projectChart = null;
    }
    const labels = yearslabels;
    const data = {
        labels: labels,
        datasets: [
            {
                label: 'Projects Started',
                data: yeardataset_start,
                type: 'bar',
                fill: false,
                backgroundColor: 'rgb(15, 192, 12, 0.4)',
                yAxisID: 'y'
            },
            {
                label: 'Projects Completed',
                data: yeardataset_end,
                type: 'bar',
                fill: false,
                backgroundColor: 'rgb(255, 99, 132, 0.4)',
                yAxisID: 'y'
            },
            {
                label: 'Funds',
                data: fundsdataset,
                type: 'line',
                fill: false,
                borderColor: 'rgb(54, 162, 235)',
                tension: 0.1,
                yAxisID: 'y2'
            }
        ]
    };

    const config = {
        type: 'bar',
        data: data,
        options: {
            responsive: true,
            plugins: {
                title: {
                    display: true,
                    text: 'Year Wise Distribution of Projects and Funds'
                },
                tooltip: {
                    callbacks: {
                        title: function(tooltipItems) {
                            return 'Details for ' + tooltipItems[0].label;
                        },
                        label: function(tooltipItem) {
                            return tooltipItem.dataset.label + ': ' + tooltipItem.raw;
                        }
                    }
                },
                legend: {
                    display: true
                }
            },
            scales: {
                x: {
                    title: {
                        display: true,
                        text: 'Year'
                    }
                },
                y: {
                    id: 'y',
                    title: {
                        display: true,
                        text: 'Number of Projects'
                    },
                    position: 'left'
                },
                y2: {
                    id: 'y2',
                    title: {
                        display: true,
                        text: 'Funds'
                    },
                    position: 'right',
                    beginAtZero: true
                }
            }
        }
    };

    const ctx = document.getElementById('projectChart').getContext('2d');
    projectChart = new Chart(ctx, config);
}

let map;

function generate_map(country_codes) {
    console.log(color_codes);
    console.log(map, 'map');
    if (typeof map !== 'undefined' && map !== null) {
        map.remove();
    }
    map = L.map('map', {
        center: [20, 0],
        zoom: 2,
        zoomControl: false,
        scrollWheelZoom: false,
        doubleClickZoom: false,
        touchZoom: false,
        dragging: false
    });

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);

    var highlightedCountries = country_codes;

    function styleFeature(feature) {
        if (highlightedCountries.includes(feature.properties.iso_a2)) {
            return {
                color: '#ff0000',
                weight: 2,
                fillOpacity: 0.4
            };
        } else {
            return {
                color: '#000',
                weight: 1,
                fillOpacity: 0.2
            };
        }
    }

    fetch(`${baseUrl}public/assets/js/in_countries.min.geojson`)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            L.geoJSON(data, {
                style: styleFeature,
                onEachFeature: function(feature, layer) {
                    if (feature.properties && feature.properties.NAME) {
                        layer.bindPopup(feature.properties.NAME);
                    } else {
                        layer.bindPopup('No name available');
                    }
                }
            }).addTo(map);
        })
        .catch(error => console.error('Error loading GeoJSON:', error));
}

function getRandomColor() {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

let goalCharts = {};

function generate_goals_charts(goalArray, goal_name, labels, datavalues, label, chartDivId, chartLabelId, chart_type) {
    console.log(datavalues, 'datavalues');
    if (goalCharts[chartDivId]) {
        goalCharts[chartDivId].destroy();
    }
    var accordion = '';

    accordion += `<div class="accordion" id="accordion${chartDivId}">`;

    goalArray.forEach((goal, index) => {
        const isActive = index === 0 ? 'show' : '';
        accordion += `
            <div class="accordion-item">
                <h2 class="accordion-header" id="heading${index}${chartDivId}">
                    <button class="accordion-button ${isActive}" type="button" data-bs-toggle="collapse" data-bs-target="#collapse${index}${chartDivId}" aria-expanded="${index === 0 ? 'true' : 'false'}" aria-controls="collapse${index}${chartDivId}">
                        ${goal.sub_goal_name}
                    </button>
                </h2>
                <div id="collapse${index}${chartDivId}" class="accordion-collapse collapse ${isActive}" aria-labelledby="heading${index}${chartDivId}" data-bs-parent="#accordion${chartDivId}">
                    <div class="accordion-body">
                        ${goal.sub_goal_description}
                    </div>
                </div>
            </div>
        `;
    });

    accordion += `</div>`;

    var template = `
        <div class="col-md-4">
            <canvas id="${chartDivId}"></canvas>
        </div>
        <div class="col-md-4 overflow-auto" style="max-height:300px">
            <div id="${chartLabelId}"></div>
        </div>
        <div class="col-md-4 overflow-auto" style="max-height:300px">
            <div>${accordion}</div>
        </div>`;

    var full_card = `
        <div class="col-md-12 mt-3 mb-3">
            <div class="card mb-4">
                <div class="card-header">${goal_name}</div>
                <div class="card-body">
                    <div class="row">
                        ${template}
                    </div>
                </div>
            </div>
        </div>`;
    
    document.getElementById('doughnut-charts-goals').insertAdjacentHTML('beforeend', full_card);

    const canvasElement = document.getElementById(chartDivId);
    if (!canvasElement) {
        console.error(`Canvas element with ID ${chartDivId} not found.`);
        return;
    }

    const backgroundColors = datavalues.map(() => getRandomColor());

    const data = {
        labels: labels,
        datasets: [{
            label: label,
            data: datavalues,
            backgroundColor: backgroundColors,
            hoverOffset: 4
        }]
    };

    let delayed;
    const config = {
        type: 'doughnut',
        data: data,
        options: {
            animation: {
                onComplete: () => {
                    delayed = true;
                },
                delay: (context) => {
                    let delay = 0;
                    if (context.type === 'data' && context.mode === 'default' && !delayed) {
                        delay = context.dataIndex * 300 + context.datasetIndex * 100;
                    }
                    return delay;
                },
            },
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        title: function(context) {
                            const datasetLabel = context[0].dataset.label || '';
                            return datasetLabel;
                        },
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.raw || '';
                            const backgroundColor = context.dataset.backgroundColor[context.dataIndex];
                            return `${label}: ${value}`;
                        }
                    }
                },
                datalabels: {
                    color: '#fff',
                    formatter: (value, context) => {
                        const total = context.dataset.data.reduce((sum, val) => sum + val, 0);
                        const percentage = ((value / total) * 100).toFixed(2);
                        return `${percentage}%`;
                    },
                    font: {
                        weight: 'bold',
                        size: 16
                    },
                    align: 'center',
                    anchor: 'center'
                }
            }
        },
        plugins: [ChartDataLabels]
    };

    try {
        goalCharts[chartDivId] = new Chart(canvasElement, config);
    } catch (e) {
        console.error(`Error creating chart with ID ${chartDivId}:`, e);
    }

    const total = data.datasets[0].data.reduce((sum, value) => sum + value, 0);
    
    const legendContainer = document.getElementById(chartLabelId);
    const legendItems = data.labels.map((label, index) => {
        const color = data.datasets[0].backgroundColor[index];
        const value = data.datasets[0].data[index];
        const percentage = ((value / total) * 100).toFixed(2);
        return `<div class="d-flex align-items-center mb-2">
            <div style="width: 20px; height: 20px; background-color: ${color};"></div>
            <span class="ms-2"><strong>${label}</strong>:<br> ${value} Projects (${percentage}%)</span>
        </div>`;
    }).join('');

    legendContainer.innerHTML = legendItems;
}

let ministryChartInstance = null;
let institutionChartInstance = null;

function ministryInstitutionChart(canvasId, dataList, colorMap, listName) {
    if (canvasId === 'ministryChart' && ministryChartInstance) {
        ministryChartInstance.destroy();
        ministryChartInstance = null;
    } else if (canvasId === 'institutionChart' && institutionChartInstance) {
        institutionChartInstance.destroy();
        institutionChartInstance = null;
    }

    const names = [];
    const counts = [];
    const colors = {};

    dataList.forEach(item => {
        const name = canvasId === 'ministryChart' ? item.ministry_name : item.institution_name;
        names.push(name);
        counts.push(parseInt(item.count, 10));

        if (!colors[item.iso]) {
            colors[item.iso] = colorMap[item.iso] || 'rgba(75, 192, 192, 0.2)';
        }
    });

    const isoLabels = [...new Set(dataList.map(item => item.iso))];
    const datasets = isoLabels.map(iso => ({
        label: iso,
        data: names.map(name => {
            const index = dataList.findIndex(item =>
                (canvasId === 'ministryChart' ? item.ministry_name : item.institution_name) === name &&
                item.iso === iso
            );
            return index !== -1 ? counts[index] : 0;
        }),
        backgroundColor: colors[iso],
        borderColor: 'rgba(0, 0, 0, 0.1)',
        borderWidth: 1
    }));

    const ctx = document.getElementById(canvasId).getContext('2d');
    const chartInstance = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: names,
            datasets: datasets
        },
        options: {
            scales: {
                x: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: 'Names'
                    }
                },
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: 'Counts'
                    }
                }
            },
            plugins: {
                legend: {
                    display: true,
                    position: 'top'
                },
                tooltip: {
                    callbacks: {
                        label: function(tooltipItem) {
                            const datasetLabel = tooltipItem.dataset.label || '';
                            const dataValue = tooltipItem.raw || 0;
                            return `${datasetLabel}: ${dataValue}`;
                        }
                    }
                }
            }
        }
    });

    if (canvasId === 'ministryChart') {
        ministryChartInstance = chartInstance;
    } else if (canvasId === 'institutionChart') {
        institutionChartInstance = chartInstance;
    }

    const listElement = document.getElementById(listName);
    if (listElement) {
        listElement.innerHTML = '';

        dataList.forEach(item => {
            const name = canvasId === 'ministryChart' ? item.ministry_name : item.institution_name;
            const iso = item.iso;
            const value = parseInt(item.count, 10);

            const div = document.createElement('div');
            div.className = 'd-flex justify-content-between align-items-center border-bottom py-2';

            const badge = document.createElement('span');
            badge.className = 'badge bg-info me-2';
            badge.textContent = iso;

            const span = document.createElement('span');
            span.className = 'flex-grow-1 text-start';
            span.textContent = name;

            const h5 = document.createElement('h5');
            h5.className = 'mb-0';
            h5.textContent = value;

            div.appendChild(badge);
            div.appendChild(span);
            div.appendChild(h5);

            listElement.appendChild(div);
        });
    } else {
        console.error(`Element with ID ${listName} not found`);
    }
}

function updateBudgetValues(amount, source) {
    return new Promise((resolve, reject) => {
        const date = new Date();
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const formattedDate = `${year}-${month}-${day}`;
        const target = document.getElementById('selected_country_currency_label').innerText;

        const requestData = {
            base: source,
            date: formattedDate,
            amount: amount,
            target: target
        };

        $.ajax({
            url: `${baseUrl}exchange`,
            method: 'POST',
            data: requestData,
            success: function(response) {
                resolve(response);
            },
            error: function(xhr, status, error) {
                console.error('AJAX request failed:');
                console.error('Status:', status);
                console.error('Error:', error);
                console.error('Response Text:', xhr.responseText);
                console.error('Status Code:', xhr.status);
                console.error('Response Headers:', xhr.getAllResponseHeaders());

                try {
                    const responseJson = JSON.parse(xhr.responseText);
                    console.error('Parsed Response JSON:', responseJson);
                } catch (e) {
                    console.error('Failed to parse response JSON:', e);
                }

                reject({
                    status: status,
                    error: error,
                    responseText: xhr.responseText,
                    statusCode: xhr.status,
                    responseHeaders: xhr.getAllResponseHeaders()
                });
            }
        });
    });
}

document.addEventListener('DOMContentLoaded', function() {
    var selectedCountries = $('.dropdown-menu input[type="checkbox"]:checked');
    if (selectedCountries.length > 0) {
        let selectedValues = [];
        selectedCountries.each(function() {
            selectedValues.push($(this).val());
        });
        console.log(selectedValues, 'selectedCountries');
        searchData(selectedValues);
    } else {
        if (type !== 'admin') {
            searchData(['IN', userCountry]);
        } else {
            searchData('');
        }
    }
});

$(document).ready(function() {
    let selectedCountries = [];

    $('.dropdown-menu input[type="checkbox"]').on('change', function() {
        selectedCountries = $('.dropdown-menu input[type="checkbox"]:checked')
            .map(function() {
                return $(this).val();
            }).get();

        if (selectedCountries.length > 0) {
            searchData(selectedCountries);
        } else {
            searchData('');
        }
    });
});

function searchData(country) {
    document.getElementById('doughnut-charts-goals').innerHTML = '';
    
    // Hide loader immediately since we're using static data
    $('#loader').hide();
    
    // Use static data instead of API call
    const data = {
        upcoming_events: 3,
        project_count: 37,
        institutions_count: 25,
        ministry_count: 8,
        project_value_count: 1500000,
        completed_project_count: 15,
        in_progress_project_count: 18,
        yet_to_start_project_count: 4,
        partnered_country: [
            {country_id: 'IN'},
            {country_id: 'GB'},
            {country_id: 'US'}
        ],
        goals: [
            {
                goal_name: 'Climate Action',
                sub_goal_object: [
                    {sub_goal_name: 'Renewable Energy', sub_goal_count: 12},
                    {sub_goal_name: 'Carbon Reduction', sub_goal_count: 8}
                ]
            },
            {
                goal_name: 'Health & Wellbeing',
                sub_goal_object: [
                    {sub_goal_name: 'Medical Research', sub_goal_count: 15},
                    {sub_goal_name: 'Public Health', sub_goal_count: 10}
                ]
            }
        ],
        // Add missing fields that are causing errors
        upcoming_events_list: [
            {
                id: 1,
                name: 'Climate Innovation Summit',
                start_date: '2025-11-15',
                end_date: '2025-11-17'
            },
            {
                id: 2,
                name: 'Health Tech Conference',
                start_date: '2025-12-01',
                end_date: '2025-12-03'
            }
        ],
        ministry_country_list_count: [
            {ministry_name: 'Ministry of Science', count: 5, iso: 'GB'},
            {ministry_name: 'Department of Technology', count: 3, iso: 'IN'}
        ],
        institution_country_list_count: [
            {institution_name: 'University of Cambridge', count: 8, iso: 'GB'},
            {institution_name: 'IIT Delhi', count: 6, iso: 'IN'}
        ],
        ministries_list: [
            {ministry_name: 'Ministry of Science', count: 5, iso: 'GB'},
            {ministry_name: 'Department of Technology', count: 3, iso: 'IN'}
        ],
        institutions_list: [
            {institution_name: 'University of Cambridge', count: 8, iso: 'GB'},
            {institution_name: 'IIT Delhi', count: 6, iso: 'IN'}
        ],
        year_project_list: [
            {year: 2023, start_date_count: 8, end_date_count: 5, total_value_in_usd: 500000},
            {year: 2024, start_date_count: 12, end_date_count: 8, total_value_in_usd: 750000},
            {year: 2025, start_date_count: 17, end_date_count: 3, total_value_in_usd: 1200000}
        ],
        country_sum_value_list: [
            {country_name: 'United Kingdom', total_value: 800000},
            {country_name: 'India', total_value: 700000}
        ]
    };
    
    console.log('Using static dashboard data:', data);
    
    document.getElementById('upcoming-events').innerText = data.upcoming_events;
    document.getElementById('project_count').innerText = data.project_count;
    document.getElementById('institutions_count').innerText = data.institutions_count;
    document.getElementById('ministries_count').innerText = data.ministry_count;
    const projectValueCount = (data.project_value_count > 0) ? parseFloat(data.project_value_count).toFixed(2) : 0;
    const currency = 'USD';

    const budgetValueUSDHTML = `
        <span id="budget_value_USD" 
              data-usd="${projectValueCount.toLocaleString()}">
            ${projectValueCount.toLocaleString()}
        </span> 
        <span id="budget_value_currency">${currency}</span>
    `;
    document.getElementById('project_value_count').innerHTML = budgetValueUSDHTML;
    document.getElementById('completed-project-count').innerText = data.completed_project_count;
    document.getElementById('in-progress-project-count').innerText = data.in_progress_project_count;
    document.getElementById('yet-to-start-project-count').innerText = data.yet_to_start_project_count;
            
    document.addEventListener('DOMContentLoaded', function() {
        if (typeof L === 'undefined') {
            console.error('Leaflet library is not loaded.');
            return;
        }
        if (data.partnered_country.length > 0) {
            console.log(data.partnered_country, 'data.partnered_country');
            generate_map(data.partnered_country.map(country => country.country_id));
        }
    });

    data.goals.forEach(goal => {
        const labels = goal.sub_goal_object.map(subGoal => subGoal.sub_goal_name);
        const datavalues = goal.sub_goal_object.map(subGoal => parseInt(subGoal.sub_goal_count, 10));
        const goalNameFormatted = goal.goal_name.replace(/\s+/g, '-').toLowerCase();

        generate_goals_charts(goal.sub_goal_object, goal.goal_name, labels, datavalues, `${goal.goal_name} Dataset`, `${goalNameFormatted}-chart`, `${goalNameFormatted}-chart-labels`, 'pie');
    });

            const ministryColorMap = {
                'United Kingdom': 'rgba(54, 162, 235, 0.2)',
                'India': 'rgba(255, 99, 132, 0.2)'
            };
            const institutionColorMap = {
                'United Kingdom': 'rgba(54, 162, 235, 0.2)',
                'India': 'rgba(255, 99, 132, 0.2)'
            };

            ministryInstitutionChart('ministryChart', data.ministries_list, ministryColorMap, 'ministry-lists');
            ministryInstitutionChart('institutionChart', data.institutions_list, institutionColorMap, 'institution-lists');

            const years = [];
            const startCounts = [];
            const endCounts = [];
            const totalValues = [];

            data.year_project_list.forEach(item => {
                years.push(item.year);
                startCounts.push(parseFloat(item.start_date_count));
                endCounts.push(parseFloat(item.end_date_count));
                totalValues.push(parseFloat(item.total_value_in_usd));
            });

            year_chart(years, startCounts, endCounts, totalValues);

            if (data.ministry_country_list_count && data.ministry_country_list_count.length > 0) {
                let titleString = data.ministry_country_list_count
                    .map(item => `<strong>${item.country_name}</strong>: ${item.count}`)
                    .join('<br>');
                document.getElementById('ministries-card').setAttribute('data-bs-toggle', 'tooltip');
                document.getElementById('ministries-card').setAttribute('data-bs-placement', 'top');
                document.getElementById('ministries-card').setAttribute('title', titleString);
            } else {
                document.getElementById('ministries-card').removeAttribute('data-bs-toggle');
                document.getElementById('ministries-card').removeAttribute('data-bs-placement');
                document.getElementById('ministries-card').removeAttribute('title');
                document.getElementById('ministries-card').removeAttribute('data-bs-original-title');
            }

            if (data.institution_country_list_count && data.institution_country_list_count.length > 0) {
                let titleString = data.institution_country_list_count
                    .map(item => `<strong>${item.country_name}</strong>: ${item.count}`)
                    .join('<br>');
                document.getElementById('institution-card').setAttribute('data-bs-toggle', 'tooltip');
                document.getElementById('institution-card').setAttribute('data-bs-placement', 'top');
                document.getElementById('institution-card').setAttribute('title', titleString);
            } else {
                document.getElementById('institution-card').removeAttribute('data-bs-toggle');
                document.getElementById('institution-card').removeAttribute('data-bs-placement');
                document.getElementById('institution-card').removeAttribute('title');
                document.getElementById('institution-card').removeAttribute('data-bs-original-title');
            }

    loadTooltip();
    let content_upcoming_events = data.upcoming_events_list.map(event => `
        <div class="text-body-secondary text-uppercase small">
            <a href="${baseUrl}country/view_event/${event.id}">${event.name}</a>
            <span class="badge bg-success w-100 text-wrap">${event.start_date} - ${event.end_date}</span>
        </div>
    `).join('');

    document.getElementById('upcoming_events_list').innerHTML = content_upcoming_events;
    country_value_modal_populate(data.country_sum_value_list);

    loadTooltip();
    exchange_project_value_currency();
    
    // Static data processing complete
    $('#loader').hide();
}

function exchange_project_value_currency() {
    const usdValue = document.getElementById('budget_value_USD').innerText;
    const sourceCurrency = document.getElementById('budget_value_currency').innerText;

    updateBudgetValues(usdValue, sourceCurrency)
        .then(response => {
            if (response.target_val && response.target_currency) {
                document.getElementById('budget_value_USD').innerText = parseFloat(response.target_val).toFixed(0);
                document.getElementById('budget_value_currency').innerText = response.target_currency;

                if (!projectChart) {
                    console.error('Chart not initialized');
                    return;
                }

                const fundsDatasetIndex = projectChart.data.datasets.findIndex(dataset => dataset.label === 'Funds');
                if (fundsDatasetIndex === -1) {
                    console.error('Funds dataset not found');
                    return;
                }

                const currentData = projectChart.data.datasets[fundsDatasetIndex].data;
                if (!currentData) {
                    console.error('Current data is undefined or null');
                    return;
                }

                const revisedDataPromises = currentData.map(value => {
                    return updateBudgetValues(value, sourceCurrency)
                        .then(result => {
                            const newValue = parseFloat(result.target_val);
                            return newValue < 0.5 ? 0 : newValue;
                        })
                        .catch(err => {
                            console.error('Error updating value:', err);
                            return value;
                        });
                });

                Promise.all(revisedDataPromises)
                    .then(updatedData => {
                        projectChart.data.datasets[fundsDatasetIndex].data = updatedData;
                        projectChart.update();
                    })
                    .catch(err => {
                        console.error('Error updating chart data:', err);
                    });
            } else {
                console.warn('Unexpected response format:', response);
            }
        })
        .catch(error => {
            console.error('Error occurred:', error);
        });
}

document.addEventListener('DOMContentLoaded', function() {
    const currencyContainer = document.querySelector('.currencydropdown');

    currencyContainer.addEventListener('click', function(e) {
        if (e.target.classList.contains('currency-dropdown')) {
            const targetCurrency = e.target.getAttribute('data-currency');
            document.getElementById('selected_country_currency_label').innerText = targetCurrency;
            exchange_project_value_currency();
        }
    });
});