/**
 * Boostify Dashboard Charts
 * Dynamic chart functionality for the dashboard
 */

(function ($) {
  "use strict";

  // Initialize charts when document is ready
  $(document).ready(function () {
    initDashboardCharts();
  });

  /**
   * Initialize all dashboard charts
   */
  function initDashboardCharts() {
    // Check if dashboard data is available
    if (typeof window.dashboardData === "undefined") {
      console.log("Dashboard data not available");
      return;
    }

    // Initialize statistics chart
    initStatsChart();

    // Initialize calendar interactions
    initCalendarInteractions();

    // Initialize range button interactions
    initRangeButtons();

    // Initialize reject button functionality
    initRejectButtons();
  }

  /**
   * Initialize the main statistics chart
   */
  function initStatsChart() {
    const ctx = document.getElementById("statsChart");
    if (!ctx) return;

    const weekStats = window.dashboardData.weekStats || [];

    // Prepare chart data
    const labels = weekStats.map((stat) => stat.day_name);
    const postData = weekStats.map((stat) => stat.posts);
    const avgData = weekStats.map(() => {
      const total = postData.reduce((sum, val) => sum + val, 0);
      return total / postData.length;
    });

    // Create gradient for posts line
    const gradientPosts = ctx
      .getContext("2d")
      .createLinearGradient(0, 0, 0, 120);
    gradientPosts.addColorStop(0, "rgba(171, 84, 219, 0.8)");
    gradientPosts.addColorStop(1, "rgba(171, 84, 219, 0.1)");

    // Create gradient for average line
    const gradientAvg = ctx.getContext("2d").createLinearGradient(0, 0, 0, 120);
    gradientAvg.addColorStop(0, "rgba(255, 255, 255, 0.3)");
    gradientAvg.addColorStop(1, "rgba(255, 255, 255, 0.05)");

    new Chart(ctx, {
      type: "line",
      data: {
        labels: labels,
        datasets: [
          {
            label: "Posts",
            data: postData,
            borderColor: "#AB54DB",
            backgroundColor: gradientPosts,
            borderWidth: 2,
            fill: true,
            tension: 0.4,
            pointBackgroundColor: "#AB54DB",
            pointBorderColor: "#fff",
            pointBorderWidth: 2,
            pointRadius: 4,
            pointHoverRadius: 6,
          },
          {
            label: "Average",
            data: avgData,
            borderColor: "rgba(255, 255, 255, 0.5)",
            backgroundColor: gradientAvg,
            borderWidth: 1,
            fill: false,
            tension: 0.4,
            pointBackgroundColor: "rgba(255, 255, 255, 0.5)",
            pointBorderColor: "#fff",
            pointBorderWidth: 1,
            pointRadius: 2,
            pointHoverRadius: 4,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false,
          },
          tooltip: {
            backgroundColor: "rgba(0, 0, 0, 0.8)",
            titleColor: "#fff",
            bodyColor: "#fff",
            borderColor: "#AB54DB",
            borderWidth: 1,
            cornerRadius: 8,
            displayColors: false,
            callbacks: {
              title: function (context) {
                return context[0].label;
              },
              label: function (context) {
                if (context.datasetIndex === 0) {
                  return "Posts: " + context.parsed.y;
                } else {
                  return "Average: " + context.parsed.y.toFixed(1);
                }
              },
            },
          },
        },
        scales: {
          x: {
            display: true,
            grid: {
              display: false,
            },
            ticks: {
              color: "rgba(255, 255, 255, 0.7)",
              font: {
                size: 10,
              },
            },
          },
          y: {
            display: true,
            grid: {
              color: "rgba(255, 255, 255, 0.1)",
              drawBorder: false,
            },
            ticks: {
              color: "rgba(255, 255, 255, 0.7)",
              font: {
                size: 10,
              },
              stepSize: 1,
            },
            border: {
              display: false,
            },
          },
        },
        interaction: {
          intersect: false,
          mode: "index",
        },
        elements: {
          point: {
            hoverBackgroundColor: "#AB54DB",
          },
        },
      },
    });
  }

  /**
   * Initialize calendar day interactions
   */
  function initCalendarInteractions() {
    $(".calendar-day").on("click", function () {
      // Remove active class from all calendar days
      $(".calendar-day").removeClass("active");

      // Add active class to clicked day
      $(this).addClass("active");

      // Get the day data and update chart if needed
      const dayIndex = $(this).index();
      const weekStats = window.dashboardData.weekStats || [];

      if (weekStats[dayIndex]) {
        updateStatsForDay(weekStats[dayIndex]);
      }
    });
  }

  /**
   * Initialize range button interactions
   */
  function initRangeButtons() {
    $(".range-btn").on("click", function () {
      // Remove active class from all range buttons
      $(".range-btn").removeClass("active");

      // Add active class to clicked button
      $(this).addClass("active");

      // Get the range type
      const range = $(this).text().toLowerCase();

      // Update chart based on range
      updateChartForRange(range);
    });
  }

  /**
   * Update statistics display for a specific day
   */
  function updateStatsForDay(dayData) {
    // Update the stats total
    $(".stats-total").text(dayData.posts);

    // Update the stats label
    $(".stats-label").text("Posts on " + dayData.day_name + " " + dayData.day);

    // You can add more dynamic updates here
    console.log("Selected day:", dayData);
  }

  /**
   * Initialize reject button functionality
   */
  function initRejectButtons() {
    $(document).on("click", ".reject", function (e) {
      e.preventDefault();

      const postId = $(this).data("post-id");
      const button = $(this);

      if (!postId) {
        console.error("No post ID found");
        return;
      }

      // Show confirmation
      if (
        !confirm(
          "Are you sure you want to reject this post? It will be moved to trash."
        )
      ) {
        return;
      }

      // Disable button and show loading
      button.prop("disabled", true).text("Rejecting...");

      // Make AJAX call to reject post
      $.ajax({
        url:
          typeof boostify_dashboard_vars !== "undefined"
            ? boostify_dashboard_vars.ajaxurl
            : "/wp-admin/admin-ajax.php",
        type: "POST",
        data: {
          action: "boostify_dashboard_reject_post",
          post_id: postId,
          nonce:
            typeof boostify_dashboard_vars !== "undefined"
              ? boostify_dashboard_vars.nonce
              : "",
        },
        success: function (response) {
          if (response.success) {
            // Remove the card from the UI
            button.closest(".pending-card").fadeOut(300, function () {
              $(this).remove();

              // Update the pending count
              updatePendingCount();
            });

            // Show success message
            showNotification("Post rejected successfully", "success");
          } else {
            showNotification(
              "Failed to reject post: " + (response.data || "Unknown error"),
              "error"
            );
            button.prop("disabled", false).text("Reject");
          }
        },
        error: function () {
          showNotification("Network error occurred", "error");
          button.prop("disabled", false).text("Reject");
        },
      });
    });
  }

  /**
   * Update pending count display
   */
  function updatePendingCount() {
    const remainingCards = $(".pending-card").length;
    $(".approval-tagline").text(
      remainingCards + " posts awaiting your review."
    );

    // If no more pending posts, show empty state
    if (remainingCards === 0) {
      $(".pending-list").html(`
                <div class="pending-card">
                    <div class="pending-card-top">
                        <img src="${boostify_dashboard_vars.pending_img}" alt="No Pending Posts">
                        <div class="pending-card-top-right">
                            <h3>No Pending Posts</h3>
                            <p>All caught up!</p>
                        </div>
                    </div>
                    <div class="pending-card-bottom">
                        <p>Great job! There are no posts waiting for approval at the moment.</p>
                    </div>
                </div>
            `);
    }
  }

  /**
   * Show notification message
   */
  function showNotification(message, type = "info") {
    // Create notification element
    const notification = $(`
            <div class="dashboard-notification ${type}" style="
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 15px 20px;
                border-radius: 8px;
                color: white;
                font-weight: 500;
                z-index: 9999;
                max-width: 300px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.3);
                transform: translateX(100%);
                transition: transform 0.3s ease;
            ">
                ${message}
            </div>
        `);

    // Set background color based on type
    const colors = {
      success: "#10B981",
      error: "#EF4444",
      info: "#3B82F6",
    };

    notification.css("background-color", colors[type] || colors.info);

    // Add to page and animate in
    $("body").append(notification);

    setTimeout(() => {
      notification.css("transform", "translateX(0)");
    }, 100);

    // Remove after 3 seconds
    setTimeout(() => {
      notification.css("transform", "translateX(100%)");
      setTimeout(() => {
        notification.remove();
      }, 300);
    }, 3000);
  }

  /**
   * Update chart for different time ranges
   */
  function updateChartForRange(range) {
    // Show loading state
    const chartContainer = $("#statsChart").closest(".stats-dashboard");
    chartContainer.addClass("loading");

    // Make AJAX call to get data for the selected range
    $.ajax({
      url:
        typeof boostify_dashboard_vars !== "undefined"
          ? boostify_dashboard_vars.ajaxurl
          : "/wp-admin/admin-ajax.php",
      type: "POST",
      data: {
        action: "boostify_dashboard_get_range_data",
        range: range,
        nonce:
          typeof boostify_dashboard_vars !== "undefined"
            ? boostify_dashboard_vars.nonce
            : "",
      },
      success: function (response) {
        chartContainer.removeClass("loading");

        if (response.success) {
          updateChartWithData(response.data, range);
        } else {
          showNotification("Failed to load chart data", "error");
        }
      },
      error: function () {
        chartContainer.removeClass("loading");
        showNotification("Network error occurred", "error");
      },
    });
  }

  /**
   * Update chart with new data
   */
  function updateChartWithData(data, range) {
    const ctx = document.getElementById("statsChart");
    if (!ctx) return;

    // Destroy existing chart if it exists
    if (window.dashboardChart) {
      window.dashboardChart.destroy();
    }

    let labels, postData, avgData;

    if (range === "month") {
      labels = data.map((stat) => stat.day);
      postData = data.map((stat) => stat.posts);
    } else if (range === "year") {
      labels = data.map((stat) => stat.month);
      postData = data.map((stat) => stat.posts);
    } else {
      labels = data.map((stat) => stat.day_name);
      postData = data.map((stat) => stat.posts);
    }

    // Calculate average
    avgData = postData.map(() => {
      const total = postData.reduce((sum, val) => sum + val, 0);
      return total / postData.length;
    });

    // Create gradients
    const gradientPosts = ctx
      .getContext("2d")
      .createLinearGradient(0, 0, 0, 120);
    gradientPosts.addColorStop(0, "rgba(171, 84, 219, 0.8)");
    gradientPosts.addColorStop(1, "rgba(171, 84, 219, 0.1)");

    const gradientAvg = ctx.getContext("2d").createLinearGradient(0, 0, 0, 120);
    gradientAvg.addColorStop(0, "rgba(255, 255, 255, 0.3)");
    gradientAvg.addColorStop(1, "rgba(255, 255, 255, 0.05)");

    // Create new chart
    window.dashboardChart = new Chart(ctx, {
      type: "line",
      data: {
        labels: labels,
        datasets: [
          {
            label: "Posts",
            data: postData,
            borderColor: "#AB54DB",
            backgroundColor: gradientPosts,
            borderWidth: 2,
            fill: true,
            tension: 0.4,
            pointBackgroundColor: "#AB54DB",
            pointBorderColor: "#fff",
            pointBorderWidth: 2,
            pointRadius: 4,
            pointHoverRadius: 6,
          },
          {
            label: "Average",
            data: avgData,
            borderColor: "rgba(255, 255, 255, 0.5)",
            backgroundColor: gradientAvg,
            borderWidth: 1,
            fill: false,
            tension: 0.4,
            pointBackgroundColor: "rgba(255, 255, 255, 0.5)",
            pointBorderColor: "#fff",
            pointBorderWidth: 1,
            pointRadius: 2,
            pointHoverRadius: 4,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false,
          },
          tooltip: {
            backgroundColor: "rgba(0, 0, 0, 0.8)",
            titleColor: "#fff",
            bodyColor: "#fff",
            borderColor: "#AB54DB",
            borderWidth: 1,
            cornerRadius: 8,
            displayColors: false,
            callbacks: {
              title: function (context) {
                return context[0].label;
              },
              label: function (context) {
                if (context.datasetIndex === 0) {
                  return "Posts: " + context.parsed.y;
                } else {
                  return "Average: " + context.parsed.y.toFixed(1);
                }
              },
            },
          },
        },
        scales: {
          x: {
            display: true,
            grid: {
              display: false,
            },
            ticks: {
              color: "rgba(255, 255, 255, 0.7)",
              font: {
                size: 10,
              },
            },
          },
          y: {
            display: true,
            grid: {
              color: "rgba(255, 255, 255, 0.1)",
              drawBorder: false,
            },
            ticks: {
              color: "rgba(255, 255, 255, 0.7)",
              font: {
                size: 10,
              },
              stepSize: 1,
            },
            border: {
              display: false,
            },
          },
        },
        interaction: {
          intersect: false,
          mode: "index",
        },
        elements: {
          point: {
            hoverBackgroundColor: "#AB54DB",
          },
        },
      },
    });

    // Update stats display
    const totalPosts = postData.reduce((sum, val) => sum + val, 0);
    $(".stats-total").text(totalPosts);
    $(".stats-label").text(
      "Total Posts - " + range.charAt(0).toUpperCase() + range.slice(1)
    );
  }

  /**
   * Utility function to format numbers
   */
  function formatNumber(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }

  /**
   * Utility function to get percentage change
   */
  function getPercentageChange(current, previous) {
    if (previous === 0) return current > 0 ? 100 : 0;
    return ((current - previous) / previous) * 100;
  }
})(jQuery);