import ConfirmModal from "Components/Modal/ConfirmModal";
import React from "react";
import { useParams } from "react-router";
import { GlobalContext, showToast } from "Src/globalContext";
import {
  deleteIdeaAPI,
  deleteSubProjectIdeaAPI,
  getAllSubProjectIdeaAPI,
} from "Src/services/projectService";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

const Idea = ({
  ideas,
  setIdeaUpdateForm,
  setIdeaAddForm,
  getAllIdeasByProjectId,
  setDeleteIdeaPayload,
}) => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const projectId = useParams();

  const [addNewIdeaUI, setAddNewIdeaUI] = React.useState(false);
  const [addNewIdeaBtnText, setAddNewIdeaBtnText] =
    React.useState("Add New Idea");
  const [updatedIdea, setUpdatedIdea] = React.useState(null);
  const [newIdea, setNewIdea] = React.useState(null);
  const [showDeleteIdeaModal, setShowDeleteIdeaModal] = React.useState(false);
  const [deleteIdeaId, setDeleteIdeaId] = React.useState(null);
  const [showActionMenu, setShowActionMenu] = React.useState(null);

  React.useEffect(() => {
    const handleClickOutside = (event) => {
      if (showActionMenu && !event.target.closest(".action-menu")) {
        setShowActionMenu(null);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [showActionMenu]);

  const handleAddNewIdeaUI = () => {
    setAddNewIdeaUI(!addNewIdeaUI);
    setAddNewIdeaBtnText(addNewIdeaUI ? "Add New Idea" : "Cancel New Idea");
  };

  const handleUpdateIdea = () => {
    let ideaKey = updatedIdea.idea_key
      .split(" ")
      .map((word) => word.charAt(0).toLowerCase() + word.slice(1))
      .join("_");
    let ideaValue = updatedIdea.idea_value.replace(/\n/g, "<br>");
    let localUpdatedIdea = {
      ...updatedIdea,
      idea_key: ideaKey,
      idea_value: ideaValue,
    };
    setIdeaUpdateForm(localUpdatedIdea);
  };

  const onChangeOldIdea = (e, idea_key) => {
    setUpdatedIdea(null);

    let updatedIdea = ideas.find((idea) => idea.idea_key === idea_key);

    updatedIdea.idea_value = e.target.value;
    setUpdatedIdea(updatedIdea);
  };

  const handleSubmitNewIdea = () => {
    if (!newIdea) {
      showToast(globalDispatch, "Cannot submit empty idea.", 3000, "error");
      return;
    }
    setIdeaAddForm(newIdea);
    setAddNewIdeaUI(!addNewIdeaUI);
    setAddNewIdeaBtnText("Add New Idea");
  };

  const onChangeNewIdea = (e) => {
    if (e.target.value !== "") {
      let new_idea_key =
        ideas.length > 0
          ? `idea_${
              parseInt(ideas?.[ideas.length - 1]?.idea_key.slice(-1)) + 1
            }`
          : "idea_1";
      setNewIdea({
        idea_key: new_idea_key,
        idea_value: e.target.value.replace(/'/g, "''"),
        // survey_id: ideas.length > 0 ? ideas[0].survey_id : null,
      });
    } else {
      setNewIdea(null);
    }
  };

  const handleDeleteAssignedIdea = async () => {
    setShowDeleteIdeaModal(false);

    const result = await deleteIdeaAPI({
      idea_id: deleteIdeaId,
      project_id: projectId.id,
    });
    if (!result.error) {
      await getAllIdeasByProjectId();
      showToast(globalDispatch, "Idea deleted", 3000, "success");
    } else {
      showToast(globalDispatch, result.message, 3000, "error");
    }
  };

  const handleDeleteIdeaModalClose = () => {
    setShowDeleteIdeaModal(false);
  };
  console.log(ideas);

  return (
    <>
      {showDeleteIdeaModal && (
        <ConfirmModal
          confirmText={`Are you sure you want to delete this idea?`}
          setModalClose={handleDeleteIdeaModalClose}
          setFormYes={handleDeleteAssignedIdea}
        />
      )}

      <div className="rounded border border-strokedark bg-boxdark p-4">
        {/* Header Section */}
        <div className="mb-6 flex items-center justify-between">
          <h3 className="text-xl font-medium text-white">Ideas</h3>
          <button
            className={`inline-flex items-center justify-center rounded px-3 py-1.5 text-center font-medium text-white transition
              ${
                addNewIdeaUI
                  ? "bg-danger hover:bg-opacity-90"
                  : "bg-primary hover:bg-opacity-90"
              }`}
            onClick={handleAddNewIdeaUI}
          >
            {addNewIdeaBtnText}
          </button>
        </div>

        {/* New Idea Form */}
        {addNewIdeaUI && (
          <div className="mb-6 space-y-4 rounded border border-strokedark bg-meta-4 p-4">
            <div className="flex items-center justify-between">
              <h4 className="text-lg font-medium text-white">New Idea</h4>
              <button
                className="inline-flex items-center justify-center rounded bg-primary px-3 py-1.5 text-center text-sm font-normal text-white hover:bg-opacity-90"
                onClick={handleSubmitNewIdea}
              >
                Save
              </button>
            </div>
            <textarea
              className="w-full rounded border border-strokedark bg-boxdark p-3 text-white placeholder-gray-400 focus:border-primary"
              rows="5"
              placeholder="Idea Description"
              onChange={(e) => onChangeNewIdea(e)}
            />
          </div>
        )}

        {/* Ideas List */}
        <div className="space-y-4">
          {ideas && ideas.length > 0 ? (
            ideas.map((idea, index) => {
              // remove <br> tags from idea value
              idea.idea_value = idea.idea_value.replace(/<br>/g, "\n");
              // idea.idea_key = 'idea_1', 'idea_2', etc.
              // convert to Idea #1, Idea #2, etc.
              idea.idea_key = idea.idea_key
                .split("_")
                .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
                .join(" ");
              const shouldShowDeleteButton =
                index > 4 || idea.subproject_ideas.length > 0;

              return (
                <div
                  key={idea.id}
                  className="rounded border border-strokedark p-4"
                >
                  <div className="mb-4 flex items-center justify-between">
                    <h4 className="text-lg font-medium text-white">
                      {idea.idea_key}
                    </h4>
                    <div className="flex items-center gap-3">
                      <button
                        className="inline-flex items-center justify-center rounded bg-primary px-3 py-1.5 text-center text-sm font-normal text-white hover:bg-opacity-90"
                        onClick={handleUpdateIdea}
                      >
                        Update
                      </button>
                      {shouldShowDeleteButton && (
                        <div className="action-menu relative">
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              setShowActionMenu(
                                showActionMenu === idea.id ? null : idea.id
                              );
                            }}
                            className="inline-flex h-9 w-9 items-center justify-center rounded-md border border-strokedark text-white hover:bg-primary/10"
                          >
                            <FontAwesomeIcon icon="fa-solid fa-ellipsis-vertical" />
                          </button>
                          {showActionMenu === idea.id && (
                            <div className="shadow-card absolute right-0 top-full z-[9] mt-2 w-40 rounded border border-strokedark bg-boxdark py-1">
                              <button
                                onClick={() => {
                                  setDeleteIdeaId(idea.id);
                                  setShowDeleteIdeaModal(true);
                                  setShowActionMenu(null);
                                }}
                                className="flex w-full items-center gap-2 px-4 py-2 text-sm font-medium text-danger hover:bg-primary/5"
                              >
                                <FontAwesomeIcon icon="fa-solid fa-trash" />
                                Delete
                              </button>
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                  <textarea
                    className="w-full rounded border border-strokedark bg-boxdark p-3 text-white placeholder-gray-400 focus:border-primary"
                    rows="5"
                    placeholder="Idea Description"
                    defaultValue={idea.idea_value}
                    onChange={(e) => onChangeOldIdea(e, idea.idea_key)}
                  />
                </div>
              );
            })
          ) : (
            <div className="rounded border border-strokedark bg-meta-4 p-4 text-center text-white">
              No ideas found
            </div>
          )}
        </div>
      </div>
    </>
  );
};

export default Idea;
