import React from "react";
import Select from "react-select";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { GlobalContext, showToast } from "Src/globalContext";
import FormMultiSelect from "Components/FormMultiSelect";

const AddIdeaForMultiSubProjectMasterProjectModal = ({
  subProjects,
  setModalClose,
  setFormYes,
}) => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const [subProjectsForSelect, setSubProjectsForSelect] = React.useState([]);
  const [selectedSubProjectIds, setSelectedSubProjectIds] = React.useState([]);
  const [subProjectOptions, setSubProjectOptions] = React.useState([]);
  const [songsForSelect, setSongsForSelect] = React.useState([]);
  const [voiceoversForSelect, setVoiceoversForSelect] = React.useState([]);

  console.log(subProjects);

  const handleSubmit = (e) => {
    e.preventDefault();

    if (selectedSubProjectIds.length === 0) {
      showToast(
        globalDispatch,
        "Please select at least one sub project",
        4000,
        "error"
      );
      return;
    }

    setFormYes({
      subproject_ids: selectedSubProjectIds,
    });
  };

  const handleSubProjectsChange = (ids) => {
    setSelectedSubProjectIds(ids);
    const options = subProjectsForSelect.filter((option) =>
      ids.includes(option.value)
    );
    setSubProjectOptions(options);
  };

  const handleSelectAll = () => {
    const ids = subProjects.map((subProject) => subProject.id);
    setSelectedSubProjectIds(ids);
    setSubProjectOptions(subProjectsForSelect);
  };

  const handleSelectAllSongs = () => {
    const ids = subProjects
      .filter((subProject) => subProject.is_song)
      .map((subProject) => subProject.id);
    setSelectedSubProjectIds(ids);
    const options = songsForSelect.filter((option) =>
      ids.includes(option.value)
    );
    setSubProjectOptions(options);
  };

  const handleSelectAllVoiceovers = () => {
    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);

    setSelectedSubProjectIds(ids);
    const options = voiceoversForSelect.filter((option) =>
      ids.includes(option.value)
    );
    setSubProjectOptions(options);
  };

  const handleClearAll = () => {
    setSelectedSubProjectIds([]);
    setSubProjectOptions([]);
  };

  React.useEffect(() => {
    if (subProjects.length > 0) {
      const songOptions = subProjects
        .filter((subProject) => subProject.is_song)
        .map((subProject) => {
          return {
            value: subProject.id,
            label: subProject.type,
          };
        });

      setSongsForSelect(songOptions);

      const voiceoverOptions = subProjects
        .filter((subProject) => {
          let subProjectType = subProject.type.replace(/[0-9]/g, "");
          subProjectType = subProjectType.replace(/\s/g, "");
          if (!subProject.is_song && subProjectType === "Voiceover") {
            return subProject;
          }
        })
        .map((subProject) => {
          return {
            value: subProject.id,
            label: subProject.type,
          };
        });

      setVoiceoversForSelect(voiceoverOptions);

      // merge songOptions and voiceoverOptions
      const options = songOptions.concat(voiceoverOptions);

      setSubProjectsForSelect(options);
    }
  }, [subProjects]);

  const selectSubProjectsRef = React.useRef(null);

  return (
    <div className="overflow-y-auto fixed inset-0 z-10">
      <div className="flex justify-center items-center px-4 pt-4 pb-20 min-h-screen text-center sm:block sm:p-0">
        <div className="fixed inset-0 transition-opacity" aria-hidden="true">
          <div className="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <span
          className="hidden sm:inline-block sm:h-screen sm:align-middle"
          aria-hidden="true"
        >
          &#8203;
        </span>
        <div
          className="inline-block overflow-hidden text-left align-bottom bg-gray-800 rounded-lg shadow-xl transition-all transform sm:my-8 sm:w-full sm:max-w-lg sm:align-middle"
          role="dialog"
          aria-modal="true"
          aria-labelledby="modal-headline"
        >
          <form>
            <div className="flex justify-between px-6 py-4 w-full border-b-2 border-gray-500 bg-slate-950">
              <h3
                className="text-2xl font-medium leading-6 text-gray-100"
                id="modal-headline"
              >
                Assign All Ideas
              </h3>
              <span
                className="absolute right-3 top-4 cursor-pointer"
                onClick={() => setModalClose(false)}
              >
                <FontAwesomeIcon
                  icon="fa-solid fa-circle-xmark"
                  width={32}
                  height={32}
                  color="#fff"
                />
              </span>
            </div>

            <div className="flex justify-start items-start p-6">
              <div className="mt-3 w-full sm:mt-0 sm:text-left">
                <div className="mb-6 text-black">
                  <label
                    className="block mb-2 text-sm font-bold text-gray-100"
                    htmlFor="subProjects"
                  >
                    Sub Projects
                  </label>
                  <FormMultiSelect
                    selectRef={selectSubProjectsRef}
                    values={selectedSubProjectIds}
                    onValuesChange={handleSubProjectsChange}
                    options={subProjectsForSelect}
                    placeholder="Sub Projects"
                  />

                  <button
                    className="inline-flex justify-center px-2 py-1 mt-2 mr-2 w-auto text-base font-medium text-white bg-blue-600 rounded-md border border-transparent shadow-sm cursor-pointer hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 sm:text-sm"
                    onClick={(e) => {
                      e.preventDefault();
                      handleSelectAll();
                    }}
                  >
                    Select All
                  </button>
                  {voiceoversForSelect.length > 0 ? (
                    <button
                      className="inline-flex justify-center px-2 py-1 mt-2 mr-2 w-auto text-base font-medium text-white bg-orange-500 rounded-md border border-transparent shadow-sm cursor-pointer hover:bg-orange-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 sm:text-sm"
                      onClick={(e) => {
                        e.preventDefault();
                        handleSelectAllVoiceovers();
                      }}
                    >
                      Voiceovers
                    </button>
                  ) : (
                    <button
                      disabled
                      className="inline-flex justify-center px-2 py-1 mt-2 mr-2 w-auto text-base font-medium text-white bg-orange-500 rounded-md border border-transparent shadow-sm cursor-pointer sm:text-sm"
                    >
                      Voiceovers
                    </button>
                  )}
                  {songsForSelect.length > 0 ? (
                    <button
                      className="inline-flex justify-center px-2 py-1 mt-2 mr-2 w-auto text-base font-medium text-white bg-sky-500 rounded-md border border-transparent shadow-sm cursor-pointer hover:bg-sky-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 sm:text-sm"
                      onClick={(e) => {
                        e.preventDefault();
                        handleSelectAllSongs();
                      }}
                    >
                      Songs
                    </button>
                  ) : (
                    <button
                      disabled
                      className="inline-flex justify-center px-2 py-1 mt-2 mr-2 w-auto text-base font-medium text-white bg-sky-500 rounded-md border border-transparent shadow-sm cursor-pointer sm:text-sm"
                    >
                      Songs
                    </button>
                  )}
                  <button
                    className="inline-flex justify-center px-2 py-1 mt-2 w-auto text-base font-medium text-white bg-red-600 rounded-md border border-transparent shadow-sm cursor-pointer hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 sm:text-sm"
                    onClick={(e) => {
                      e.preventDefault();
                      handleClearAll();
                    }}
                  >
                    Clear All
                  </button>
                </div>
              </div>
            </div>

            <div className="flex flex-row-reverse px-6 py-4 border-t-2 border-gray-500 bg-slate-950">
              <div
                onClick={(e) => handleSubmit(e)}
                className="inline-flex justify-center px-4 py-2 ml-3 w-auto text-base font-medium text-white bg-green-600 rounded-md border border-transparent shadow-sm cursor-pointer hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 sm:text-sm"
              >
                Yes
              </div>
              <div
                className="inline-flex justify-center px-4 py-2 ml-3 w-auto text-base font-medium text-white bg-red-600 rounded-md border border-transparent shadow-sm cursor-pointer hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 sm:text-sm"
                onClick={() => setModalClose(false)}
              >
                Cancel
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default AddIdeaForMultiSubProjectMasterProjectModal;
