/**
 * Dashboard JavaScript Functions
 * Contains all chart configurations and dashboard interactions
 */

// Dashboard Configuration
const DashboardConfig = {
    colors: {
        primary: "#1976d2",
        success: "#10b759",
        warning: "#f1b44c",
        info: "#3490dc",
        secondary: "#6c757d",
        danger: "#dc3545",
    },
    chartDefaults: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: false,
            },
        },
    },
};

// Initialize Dashboard when DOM is loaded
document.addEventListener("DOMContentLoaded", function () {
    console.log("Dashboard initializing...");
    initializeCharts();
    initializeInteractions();
    animateCounters();
    updateClock();
    loadRecentActivities();
});

/**
 * Initialize all charts
 */
function initializeCharts() {
    initUploadChart();
    initServiceChart();
}

/**
 * Upload Activity Line Chart
 */
function initUploadChart() {
    const uploadCtx = document.getElementById("uploadChart");
    if (!uploadCtx) {
        console.log("Upload chart element not found");
        return;
    }

    console.log("Initializing upload chart...");

    // Get monthly data from dashboard or use sample data
    const monthlyData = window.dashboardData?.monthlyData || {
        labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
        uploads: [12, 19, 8, 15, 22, 18],
    };

    new Chart(uploadCtx.getContext("2d"), {
        type: "line",
        data: {
            labels: monthlyData.labels || [
                "Jan",
                "Feb",
                "Mar",
                "Apr",
                "May",
                "Jun",
            ],
            datasets: [
                {
                    label: "Document Uploads",
                    data: monthlyData.uploads || [12, 19, 8, 15, 22, 18],
                    borderColor: DashboardConfig.colors.primary,
                    backgroundColor: DashboardConfig.colors.primary + "20",
                    borderWidth: 3,
                    fill: true,
                    tension: 0.4,
                    pointBackgroundColor: DashboardConfig.colors.primary,
                    pointBorderColor: "#fff",
                    pointBorderWidth: 2,
                    pointRadius: 5,
                    pointHoverRadius: 7,
                },
            ],
        },
        options: {
            ...DashboardConfig.chartDefaults,
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: "rgba(0,0,0,0.05)",
                        borderDash: [2, 2],
                    },
                    ticks: {
                        color: "#6c757d",
                        font: {
                            size: 12,
                        },
                        callback: function (value) {
                            return Math.floor(value);
                        },
                    },
                },
                x: {
                    grid: {
                        display: false,
                    },
                    ticks: {
                        color: "#6c757d",
                        font: {
                            size: 12,
                        },
                    },
                },
            },
            interaction: {
                intersect: false,
                mode: "index",
            },
            plugins: {
                tooltip: {
                    backgroundColor: "rgba(0,0,0,0.8)",
                    titleColor: "#fff",
                    bodyColor: "#fff",
                    borderColor: DashboardConfig.colors.primary,
                    borderWidth: 1,
                    cornerRadius: 6,
                    displayColors: false,
                    callbacks: {
                        label: function (context) {
                            return `Uploads: ${context.parsed.y}`;
                        },
                    },
                },
            },
        },
    });
}

/**
 * Service Status Doughnut Chart
 */
function initServiceChart() {
    const serviceCtx = document.getElementById("serviceChart");
    if (!serviceCtx) {
        console.log("Service chart element not found");
        return;
    }

    console.log("Initializing service chart...");

    // Get data from global window object (passed from Blade template)
    const freeServices = window.dashboardData?.freeServices || 3;
    const paidServices = window.dashboardData?.paidServices || 2;

    console.log("Chart data:", { freeServices, paidServices });

    new Chart(serviceCtx.getContext("2d"), {
        type: "doughnut",
        data: {
            labels: ["Free Services", "Paid Services"],
            datasets: [
                {
                    data: [freeServices, paidServices],
                    backgroundColor: [
                        DashboardConfig.colors.success,
                        DashboardConfig.colors.warning,
                    ],
                    borderWidth: 0,
                    hoverOffset: 4,
                },
            ],
        },
        options: {
            ...DashboardConfig.chartDefaults,
            cutout: "70%",
            plugins: {
                tooltip: {
                    backgroundColor: "rgba(0,0,0,0.8)",
                    titleColor: "#fff",
                    bodyColor: "#fff",
                    cornerRadius: 6,
                    displayColors: true,
                    callbacks: {
                        label: function (context) {
                            const label = context.label || "";
                            const value = context.parsed;
                            const total = context.dataset.data.reduce(
                                (a, b) => a + b,
                                0
                            );
                            const percentage = Math.round(
                                (value / total) * 100
                            );
                            return `${label}: ${value} (${percentage}%)`;
                        },
                    },
                },
            },
            onHover: (event, activeElements) => {
                event.native.target.style.cursor =
                    activeElements.length > 0 ? "pointer" : "default";
            },
        },
    });
}

/**
 * Initialize dashboard interactions
 */
function initializeInteractions() {
    // Action card hover effects
    const actionCards = document.querySelectorAll(".action-card");
    actionCards.forEach((card) => {
        card.addEventListener("mouseenter", function () {
            this.style.transform = "translateY(-2px)";
            this.style.transition = "all 0.3s ease";
        });

        card.addEventListener("mouseleave", function () {
            this.style.transform = "translateY(0)";
        });
    });

    // Dashboard card fade-in animation
    const dashboardCards = document.querySelectorAll(".dashboard-card");
    dashboardCards.forEach((card, index) => {
        card.style.opacity = "0";
        card.style.transform = "translateY(20px)";

        setTimeout(() => {
            card.style.transition = "all 0.5s ease";
            card.style.opacity = "1";
            card.style.transform = "translateY(0)";
        }, index * 100);
    });

    // Activity timeline animation
    const activityItems = document.querySelectorAll(".activity-item");
    activityItems.forEach((item, index) => {
        item.style.opacity = "0";
        item.style.transform = "translateX(-20px)";

        setTimeout(() => {
            item.style.transition = "all 0.3s ease";
            item.style.opacity = "1";
            item.style.transform = "translateX(0)";
        }, dashboardCards.length * 100 + index * 200);
    });

    // Real-time clock update
    setInterval(updateClock, 60000); // Update every minute

    // Add refresh button functionality
    addRefreshButton();

    // Initialize tooltips if Bootstrap is available
    if (typeof bootstrap !== "undefined") {
        const tooltipTriggerList = [].slice.call(
            document.querySelectorAll('[data-bs-toggle="tooltip"]')
        );
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }
}

/**
 * Add refresh button to dashboard
 */
function addRefreshButton() {
    const pageHeader = document.querySelector(".page-header-content .d-flex");
    if (pageHeader) {
        const refreshButton = document.createElement("button");
        refreshButton.className = "btn btn-light btn-sm ms-2";
        refreshButton.innerHTML = '<i class="ri-refresh-line"></i>';
        refreshButton.title = "Refresh Dashboard";
        refreshButton.onclick = refreshDashboard;

        const rightSide = pageHeader.querySelector(".d-none.d-md-block");
        if (rightSide) {
            rightSide.appendChild(refreshButton);
        }
    }
}

/**
 * Update the clock display
 */
function updateClock() {
    const clockElement = document.querySelector(".fw-medium.text-dark");
    if (clockElement) {
        const now = new Date();
        const options = {
            year: "numeric",
            month: "short",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
            hour12: true,
        };
        clockElement.textContent = now.toLocaleDateString("en-US", options);
    }
}

/**
 * Animate counter numbers
 */
function animateCounters() {
    const counters = document.querySelectorAll(".dashboard-card h4");

    counters.forEach((counter, index) => {
        // Delay animation based on card index
        setTimeout(() => {
            const targetText = counter.textContent.trim();
            const target = parseInt(targetText.replace(/[^\d]/g, "")) || 0;

            if (target === 0) return;

            const duration = 2000; // 2 seconds
            const increment = target / (duration / 50); // 50ms intervals
            let current = 0;

            counter.textContent = "0";

            const timer = setInterval(() => {
                current += increment;
                if (current >= target) {
                    counter.textContent = targetText; // Restore original formatting
                    clearInterval(timer);
                } else {
                    counter.textContent = Math.ceil(current).toString();
                }
            }, 50);
        }, index * 200);
    });
}

/**
 * Load recent activities
 */
function loadRecentActivities() {
    // This can be extended to load activities via AJAX
    const activityContainer = document.querySelector(".activity-timeline");
    if (!activityContainer) return;

    // Sample activities if not provided by server
    if (!window.dashboardData?.recentActivities) {
        const sampleActivities = [
            {
                icon: "ri-upload-line",
                color: "success",
                title: "Document Uploaded",
                description: "New document uploaded successfully",
                time: "2 hours ago",
            },
            {
                icon: "ri-check-line",
                color: "info",
                title: "Service Accessed",
                description: "User accessed service dashboard",
                time: "5 hours ago",
            },
            {
                icon: "ri-time-line",
                color: "warning",
                title: "Payment Pending",
                description: "Service payment required",
                time: "1 day ago",
            },
        ];

        displayActivities(sampleActivities);
    }
}

/**
 * Display activities in timeline
 */
function displayActivities(activities) {
    const timeline = document.querySelector(".activity-timeline");
    if (!timeline) return;

    timeline.innerHTML = "";

    activities.forEach((activity) => {
        const activityItem = document.createElement("div");
        activityItem.className = "activity-item";
        activityItem.innerHTML = `
            <div class="activity-icon bg-${activity.color}">
                <i class="${activity.icon} font-size-12"></i>
            </div>
            <div class="activity-content">
                <h6 class="mb-1 font-size-13">${activity.title}</h6>
                <p class="text-muted mb-1 font-size-12">${activity.description}</p>
                <span class="text-muted font-size-11">${activity.time}</span>
            </div>
        `;
        timeline.appendChild(activityItem);
    });
}

/**
 * Refresh dashboard data
 */
function refreshDashboard() {
    console.log("Refreshing dashboard...");

    // Add loading state
    const cards = document.querySelectorAll(".dashboard-card");
    cards.forEach((card) => {
        card.style.opacity = "0.7";
        card.style.pointerEvents = "none";
    });

    // Show loading indicator
    showLoadingIndicator();

    // Fetch fresh data via AJAX
    fetchDashboardData()
        .then((data) => {
            updateDashboardData(data);
        })
        .catch((error) => {
            console.error("Failed to refresh dashboard:", error);
            handleError(error, "Dashboard Refresh");
        })
        .finally(() => {
            // Remove loading state
            cards.forEach((card) => {
                card.style.opacity = "1";
                card.style.pointerEvents = "auto";
            });
            hideLoadingIndicator();
        });
}

/**
 * Fetch dashboard data via AJAX
 */
async function fetchDashboardData() {
    const response = await fetch("/admin/dashboard/data", {
        method: "GET",
        headers: {
            Accept: "application/json",
            "X-Requested-With": "XMLHttpRequest",
        },
    });

    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.json();
}

/**
 * Update dashboard with fresh data
 */
function updateDashboardData(data) {
    // Update counter values
    const counters = {
        "Available Services": data.total_services,
        "Total Uploads": data.total_documents,
        "Pending Reviews": data.pending_payments,
        Completed: data.completed_payments,
    };

    Object.entries(counters).forEach(([label, value]) => {
        const counter = Array.from(
            document.querySelectorAll(".dashboard-card h4")
        ).find((h4) => {
            const cardText = h4.closest(".card").textContent;
            return cardText.includes(label);
        });

        if (counter) {
            counter.textContent = value.toString();
        }
    });

    // Update recent activities
    if (data.recent_activities) {
        displayActivities(data.recent_activities);
    }

    // Re-animate counters
    setTimeout(() => {
        animateCounters();
    }, 100);
}

/**
 * Show loading indicator
 */
function showLoadingIndicator() {
    const existing = document.querySelector(".loading-overlay");
    if (existing) return;

    const overlay = document.createElement("div");
    overlay.className = "loading-overlay";
    overlay.innerHTML = `
        <div class="loading-content">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <div class="mt-2">Refreshing data...</div>
        </div>
    `;
    overlay.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(255,255,255,0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
        backdrop-filter: blur(2px);
    `;

    document.body.appendChild(overlay);
}

/**
 * Hide loading indicator
 */
function hideLoadingIndicator() {
    const overlay = document.querySelector(".loading-overlay");
    if (overlay) {
        overlay.remove();
    }
}

/**
 * Handle errors
 */
function handleError(error, context) {
    console.error(`Dashboard Error (${context}):`, error);

    // Show user-friendly error message
    showNotification(
        "Some dashboard features may not be working properly.",
        "warning"
    );
}

/**
 * Show notification
 */
function showNotification(message, type = "info") {
    const toast = document.createElement("div");
    toast.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    toast.style.cssText =
        "top: 20px; right: 20px; z-index: 10000; min-width: 300px;";
    toast.innerHTML = `
        <strong>${
            type.charAt(0).toUpperCase() + type.slice(1)
        }:</strong> ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(toast);

    // Auto remove after 5 seconds
    setTimeout(() => {
        if (toast.parentNode) {
            toast.remove();
        }
    }, 5000);
}

/**
 * Export dashboard data
 */
function exportData(type = "payments") {
    showLoadingIndicator();

    fetch(`/admin/dashboard/export?type=${type}`, {
        method: "GET",
        headers: {
            Accept: "application/json",
            "X-Requested-With": "XMLHttpRequest",
        },
    })
        .then((response) => response.json())
        .then((data) => {
            // Create and download file
            const blob = new Blob([JSON.stringify(data.data, null, 2)], {
                type: "application/json",
            });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url;
            a.download = data.filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);

            showNotification(`${type} data exported successfully!`, "success");
        })
        .catch((error) => {
            console.error("Export failed:", error);
            showNotification("Export failed. Please try again.", "danger");
        })
        .finally(() => {
            hideLoadingIndicator();
        });
}

/**
 * Export functions for external use
 */
window.DashboardApp = {
    refresh: refreshDashboard,
    config: DashboardConfig,
    updateClock: updateClock,
    animateCounters: animateCounters,
    exportData: exportData,
    showNotification: showNotification,
};

// Global error handler
window.addEventListener("error", function (e) {
    handleError(e.error, "Global Error");
});

// Handle Chart.js not loaded
if (typeof Chart === "undefined") {
    console.error(
        "Chart.js is not loaded. Please include Chart.js before dashboard.js"
    );
    handleError(new Error("Chart.js not found"), "Chart.js Missing");
} else {
    console.log("Dashboard.js loaded successfully with Chart.js support");
}

// Performance monitoring
window.addEventListener("load", function () {
    const loadTime = performance.now();
    console.log(`Dashboard loaded in ${Math.round(loadTime)}ms`);
});

console.log("Dashboard.js initialized successfully");
