import React from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Checkbox from "Components/Checkbox";
import { GlobalContext, showToast } from "Src/globalContext";
import { addAndAssignIdeaToMultiSubProjectsAPI } from "Src/services/projectService";
import ConfirmModal from "Components/Modal/ConfirmModal";

const AssignIdeaModalOfMasterProject = ({
  setModalClose,
  setAssignedIdeaForm,
  handleAddIdeaForMultiSubProject,
  subProjects,
  theme,
  getAllSubProjectIdea,
}) => {
  const { state, dispatch } = React.useContext(GlobalContext);
  const { projectIdeas: ideas, assignedIdeas } = state;
  console.log(ideas);
  console.log(subProjects);

  const [isCheck, setIsCheck] = React.useState([]);
  const [isCheckAll, setIsCheckAll] = React.useState(false);

  const [isCheckAllVoiceOver, setIsCheckAllVoiceOver] = React.useState(false);
  const [isCheckAllSongs, setIsCheckAllSongs] = React.useState(false);
  const [selectedSubProjectIds, setSelectedSubProjectIds] = React.useState([]);

  const [showVoiceoverConfirm, setShowVoiceoverConfirm] = React.useState(false);
  const [showSongsConfirm, setShowSongsConfirm] = React.useState(false);
  const [confirmMessage, setConfirmMessage] = React.useState("");

  const handleSelectAllSongs = async () => {
    // Get list of song projects
    const songProjects = subProjects.filter((subProject) => subProject.is_song);

    console.log(songProjects);

    if (songProjects.length === 0) {
      showToast(dispatch, "No song sub-projects found", 5000, "error");
      return;
    }

    // Create confirmation message with HTML list
    setConfirmMessage(
      `<div>
        <p>Are you sure you want to add the following song projects?</p>
        <ul class="pl-5 mt-2 list-disc">
          ${songProjects
            .map((project) => `<li>${project.type_name}</li>`)
            .join("")}
        </ul>
      </div>`
    );
    setShowSongsConfirm(true);
  };

  const handleConfirmSongs = async () => {
    const ids = subProjects
      .filter((subProject) => subProject.is_song)
      .map((subProject) => subProject.id);
    setSelectedSubProjectIds(ids);
    setShowSongsConfirm(false);
    await handleAddIdeaForMultiSubProject(ids);

    await getAllSubProjectIdea();
  };

  const handleSelectAllVoiceovers = async () => {
    // Get list of voiceover projects
    const voiceoverProjects = subProjects.filter((row) => {
      let subProjectType = row.type_name
        .replace(/[0-9]/g, "")
        .replace(/\s/g, "");
      return !row.is_song && subProjectType === "Voiceover";
    });

    if (voiceoverProjects.length === 0) {
      showToast(dispatch, "No voiceover sub-projects found", 5000, "error");
      return;
    }

    // Create confirmation message with HTML list
    setConfirmMessage(
      `<div>
        <p>Are you sure you want to add the following voiceover projects?</p>
        <ul class="pl-5 mt-2 list-disc">
          ${voiceoverProjects
            .map((project) => `<li>${project.type_name}</li>`)
            .join("")}
        </ul>
      </div>`
    );
    setShowVoiceoverConfirm(true);
  };

  const handleConfirmVoiceovers = async () => {
    const ids = subProjects
      .filter((row) => {
        let subProjectType = row.type_name.replace(/[0-9]/g, "");
        subProjectType = subProjectType.replace(/\s/g, "");
        if (!row.is_song && subProjectType === "Voiceover") {
          return row.id;
        }
      })
      .map((subProject) => subProject.id);
    setIsCheckAllVoiceOver(true);
    setSelectedSubProjectIds(ids);
    setShowVoiceoverConfirm(false);
    await handleAddIdeaForMultiSubProject(ids);

    await getAllSubProjectIdea();
  };

  const handleCheckboxClick = (e) => {
    let { id, checked } = e.target;
    id = parseInt(id);
    if (checked) {
      setIsCheck([...isCheck, id]);
    } else {
      setIsCheck(isCheck.filter((item) => item !== id));
      setIsCheckAll(false);
    }
  };

  const handleCheckboxSelectAll = (e) => {
    setIsCheckAll(!isCheckAll);
    setIsCheck(ideas.map((li) => li.id));
    if (isCheckAll) {
      setIsCheck([]);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    setAssignedIdeaForm(isCheck, selectedSubProjectIds);
  };

  const assignIdeasCheckboxes =
    ideas &&
    ideas.length > 0 &&
    ideas.map(({ id, idea_key, idea_value, subproject_ideas }) => {
      idea_value = idea_value.replace(/\n/g, "<br>");
      idea_key = idea_key
        .split("_")
        .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
        .join(" ");
      return (
        <div key={id} className="flex flex-row items-start">
          <Checkbox
            key={id}
            type="checkbox"
            name="idea_ids"
            id={id}
            handleClick={handleCheckboxClick}
            isChecked={isCheck.includes(id)}
          />
          <label
            className="ml-2 text-sm font-medium text-gray-100"
            htmlFor="idea_ids"
          >
            {idea_key}
            <p
              id="helper-checkbox-text"
              className="text-xs font-normal text-gray-300"
              dangerouslySetInnerHTML={{ __html: idea_value }}
            />
            <span className="text-white">Assigned to:&nbsp;</span>
            {subproject_ideas && subproject_ideas.length > 0 ? (
              subproject_ideas.map((subproject_idea, index) => {
                return (
                  <span key={index} className="text-white">
                    {subproject_idea.subproject_type_name},{" "}
                  </span>
                );
              })
            ) : (
              <span className="text-white">No assigned sub-project found</span>
            )}
          </label>
        </div>
      );
    });

  React.useEffect(() => {
    if (assignedIdeas && assignedIdeas.length > 0) {
      setIsCheck([]);
      assignedIdeas.map((assignedIdea) => {
        setIsCheck((isCheck) => [...isCheck, assignedIdea.idea_id]);
      });

      if (assignedIdeas.length === ideas.length) {
        setIsCheckAll(true);
      }
    }
  }, [assignedIdeas, ideas]);

  return (
    <>
      <div className="flex fixed inset-0 z-50 justify-center items-center">
        <div
          className="fixed inset-0 backdrop-blur-sm bg-black/50"
          onClick={() => setModalClose(false)}
        />
        <div className="w-full max-w-xl rounded border transition-all transform shadow-default border-strokedark bg-boxdark">
          {/* Modal Header */}
          <div className="flex justify-between items-center px-6 py-4 border-b border-stroke">
            <div className="flex gap-3 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-lightbulb"
                className="text-xl text-primary"
              />
              <h3 className="text-xl font-medium text-white">
                Assign Ideas to Sub-Projects
              </h3>
            </div>
            <button
              onClick={() => setModalClose(false)}
              className="hover:text-primary"
            >
              <FontAwesomeIcon icon="fa-solid fa-xmark" className="text-2xl" />
            </button>
          </div>

          {/* Theme Section */}
          <div className="px-6 py-4 border-b border-stroke">
            <div className="flex flex-col gap-2">
              <h4 className="text-sm font-medium text-bodydark2">
                Theme of the Routine
              </h4>
              <p className="text-base text-white">
                {theme || "No theme specified"}
              </p>
            </div>
          </div>

          {/* Quick Actions */}
          <div className="px-6 py-4 border-b border-stroke">
            <div className="flex flex-wrap gap-3">
              <button
                onClick={() => handleSelectAllVoiceovers()}
                className="px-4 py-2 text-sm font-medium text-white rounded-sm bg-primary hover:bg-opacity-90"
              >
                Add All Voiceover
              </button>
              <button
                onClick={() => handleSelectAllSongs()}
                className="px-4 py-2 text-sm font-medium text-white rounded-sm bg-meta-5 hover:bg-opacity-90"
              >
                Add All Songs
              </button>
            </div>
          </div>

          {/* Ideas List */}
          <div className="custom-overflow max-h-[60vh] overflow-y-auto px-6 py-4">
            <div className="flex items-center mb-4">
              <Checkbox
                type="checkbox"
                name="selectAll"
                id="selectAll"
                handleClick={handleCheckboxSelectAll}
                isChecked={isCheckAll}
              />
              <label className="ml-2 text-sm font-medium text-white">
                Select All Ideas
              </label>
            </div>

            {ideas?.length > 0 ? (
              <div className="space-y-4">
                {ideas.map(
                  ({ id, idea_key, idea_value, subproject_ideas }, index) => {
                    const ideaValue = idea_value.replace(/\n/g, "<br>");
                    const ideaKey = idea_key
                      .split("_")
                      .map(
                        (word) => word.charAt(0).toUpperCase() + word.slice(1)
                      )
                      .join(" ");

                    return (
                      <div
                        key={id}
                        className="p-4 rounded border border-stroke bg-boxdark-2"
                      >
                        <div className="flex gap-3 items-start">
                          <Checkbox
                            type="checkbox"
                            name="idea_ids"
                            id={id}
                            handleClick={handleCheckboxClick}
                            isChecked={isCheck.includes(id)}
                          />
                          <div className="flex-1">
                            {/* Idea Header */}
                            <div className="flex gap-2 items-center mb-2">
                              <span className="flex w-6 h-6 text-sm text-white">
                                {index + 1}
                              </span>
                              <span className="text-sm font-medium text-white">
                                {idea_key}
                              </span>
                            </div>
                            {/* Idea Description */}
                            <p className="text-xs font-normal text-gray-300">
                              {ideaValue}
                            </p>
                            {/* Assigned Sub-Projects */}
                            <div className="mt-2">
                              <span className="text-sm text-white">
                                Assigned to:&nbsp;
                              </span>
                              {subproject_ideas &&
                              subproject_ideas.length > 0 ? (
                                <span className="text-sm text-gray-300">
                                  {subproject_ideas.map((subproject_idea) => (
                                    <span
                                      key={subproject_idea.id}
                                      className="text-sm text-gray-300"
                                    >
                                      {subproject_idea.subproject_type_name},{" "}
                                    </span>
                                  ))}
                                </span>
                              ) : (
                                <span className="text-sm text-gray-300">
                                  No assigned sub-project found
                                </span>
                              )}
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  }
                )}
              </div>
            ) : (
              <div className="text-sm text-center text-gray-300">
                No ideas found
              </div>
            )}
          </div>

          {/* Save and Cancel Buttons */}
          <div className="px-6 py-4 border-t border-stroke">
            <div className="flex gap-2">
              <button
                className="flex justify-center items-center px-6 py-2 w-full text-sm font-medium text-white rounded-sm bg-primary hover:bg-opacity-90"
                onClick={(e) => handleSubmit(e)}
              >
                Save
              </button>
              <button
                className="flex justify-center items-center px-6 py-2 w-full text-sm font-medium text-white rounded-sm bg-danger hover:bg-opacity-90"
                onClick={() => setModalClose(false)}
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      </div>
      {showVoiceoverConfirm && (
        <ConfirmModal
          confirmText={
            <div dangerouslySetInnerHTML={{ __html: confirmMessage }} />
          }
          setModalClose={() => setShowVoiceoverConfirm(false)}
          setFormYes={handleConfirmVoiceovers}
          showAsList={true}
        />
      )}
      {showSongsConfirm && (
        <ConfirmModal
          confirmText={
            <div dangerouslySetInnerHTML={{ __html: confirmMessage }} />
          }
          setModalClose={() => setShowSongsConfirm(false)}
          setFormYes={handleConfirmSongs}
          showAsList={true}
        />
      )}
    </>
  );
};

export default AssignIdeaModalOfMasterProject;
