(function (blocks, element, components) {
  var el = element.createElement;
  var useState = element.useState;
  var useEffect = element.useEffect;
  var SelectControl = components.SelectControl;

  blocks.registerBlockType("bc-forum/block", {
    title: "Bc Forum",
    icon: "admin-comments",
    category: "widgets",
    attributes: {
      selectedForum: {
        type: "string",
      },
    },

    edit: function (props) {
      var [options, setOptions] = useState([]);
      var selectedForum = props.attributes.selectedForum;

      useEffect(() => {
        // Fetch the forum titles from the server
        var ajaxurl = window.bcforum_ajax_object.ajax_url; // Get the AJAX URL

        fetch(ajaxurl + "?action=get_bc_forum_titles")
          .then((response) => {
            if (!response.ok) {
              throw new Error("Network response was not ok");
            }
            return response.json();
          })
          .then((data) => {
            if (!Array.isArray(data.data)) {
              throw new Error("Invalid data format");
            }
            const formattedOptions = data.data.map((item) => ({
              label: item.title,
              value: item.id,
            }));
            setOptions(formattedOptions);
          })
          .catch((error) => {
            console.error("Error fetching forum titles:", error);
          });
      }, []);

      return el(
        "div",
        { className: "bc-forum-block" },
        el(
          "span",
          {
            className: "dashicon dashicons dashicons-admin-comments",
          },
          ""
        ),
        "BC Forum",
        el(SelectControl, {
          label: "Select Forum",
          value: selectedForum,
          options: options,
          onChange: (value) => {
            props.setAttributes({ selectedForum: value });
          },
        })
      );
    },
    save: function (props) {
      return null;
    },
  });
})(window.wp.blocks, window.wp.element, window.wp.components);

jQuery(document).ready(function ($) {
  $(".approve-question").on("click", function (e) {
    e.preventDefault();

    var questionId = $(this).data("question-id");

    $.ajax({
      url: ajaxurl,
      method: "POST",
      data: {
        action: "bcforum_approve_question",
        question_id: questionId,
        security: window.bcforum_ajax_object.nonceSecurity,
      },
      success: function (response) {
        if (response.success) {
          location.reload();
        } else {
        }
      },
    });
  });
  $(".approve-answer").on("click", function (e) {
    e.preventDefault();

    var answerId = $(this).data("answer-id");

    $.ajax({
      url: ajaxurl,
      method: "POST",
      data: {
        action: "bcforum_approve_answer",
        answer_id: answerId,
        security: window.bcforum_ajax_object.nonceSecurity,
      },
      success: function (response) {
        if (response.success) {
          location.reload();
        } else {
        }
      },
    });
  });
  $(".delete-answer").on("click", function (e) {
    e.preventDefault();
    var deleteLink = $(this);

    var answerId = deleteLink.data("answer-id");

    $.ajax({
      url: ajaxurl,
      method: "POST",
      data: {
        action: "bcforum_delete_answer",
        answer_id: answerId,
        security: window.bcforum_ajax_object.nonceSecurity,
      },
      success: function (response) {
        if (response.success) {
          // Ask for confirmation before deleting
          if (confirm("Are you sure you want to delete this answer?")) {
            // Remove the corresponding element from the UI
            deleteLink.closest("tr").remove();
          }
        } else {
          alert(response.data);
        }
      },
    });
  });
  // Generic delete function
  function handleDelete(deleteLink, id, action, idName) {
    if (confirm(`Are you sure you want to delete this ${idName}?`)) {
      $.ajax({
        url: ajaxurl,
        type: "POST",
        data: {
          action: action,
          [`${idName}_id`]: id,
          security: window.bcforum_ajax_object.nonceSecurity,
        },
        success: function (response) {
          if (response.success) {
            // Remove the corresponding element from the UI
            deleteLink.closest("tr").remove();
          } else {
            alert(response.data);
          }
        },
        error: function () {
          alert("An error occurred while processing your request.");
        },
      });
    }
  }
  // Handle question deletion
  $(document).on("click", ".delete-question", function (e) {
    e.preventDefault();
    var deleteLink = $(this);
    var questionId = deleteLink.data("question-id");
    handleDelete(deleteLink, questionId, "bcforum_delete_question", "question");
  });
  // File: bc-forum.js
  jQuery(document).ready(function ($) {
    $(".delete-forum").on("click", function (e) {
      e.preventDefault();

      if (!confirm("Are you sure you want to delete this forum?")) return;

      const forumId = $(this).data("forum-id");

      $.post(
        ajaxurl,
        {
          action: "bcforum_delete_forum",
          security: window.bcforum_ajax_object.nonceSecurity,
          forum_id: forumId,
        },
        function (response) {
          if (response.success) {
            alert(response.data);
            location.reload(); // reload the page
          } else {
            alert("Error: " + response.data);
          }
        }
      );
    });
  });
});
