import React from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Checkbox from "Components/Checkbox";
import { GlobalContext } from "Src/globalContext";

const AssignIdea = ({
  ideas,
  // assignedIdeas,
  theme,
  setModalClose,
  setAssignedIdeaForm,
}) => {
  const { state } = React.useContext(GlobalContext);
  const { assignedIdeas } = state;

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

  // assignedIdeas.length === ideas.length ? true : false
  // const [isCheckAll, setIsCheckAll] = React.useState(false);

  // 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 handleCheckboxClick = (e) => {
    const id = parseInt(e.target.id);
    setIsCheck((current) =>
      e.target.checked
        ? [...current, id]
        : current.filter((item) => item !== id)
    );
  };

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

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

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

  const assignIdeasCheckboxes =
    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: </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]);

  React.useEffect(() => {
    setIsCheckAll(isCheck.length === ideas.length);
  }, [isCheck, ideas.length]);

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

        {/* Ideas List */}
        <div className="max-h-[60vh] overflow-y-auto px-6 py-4">
          <div className="mb-4 flex items-center">
            <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="rounded border border-stroke bg-boxdark-2 p-4"
                    >
                      <div className="flex items-start gap-3">
                        <Checkbox
                          type="checkbox"
                          name="idea_ids"
                          id={id}
                          handleClick={handleCheckboxClick}
                          isChecked={isCheck.includes(id)}
                        />
                        <div className="flex-1">
                          {/* Idea Header */}
                          <div className="mb-2 flex items-center gap-2">
                            <span className="flex h-6 w-6 items-center justify-center rounded-full bg-primary text-xs font-medium text-white">
                              {index + 1}
                            </span>
                            <h5 className="text-sm font-medium text-bodydark2">
                              {ideaKey}
                            </h5>
                          </div>

                          {/* Idea Content */}
                          <p
                            className="mb-2 whitespace-pre-line text-white"
                            dangerouslySetInnerHTML={{ __html: ideaValue }}
                          />

                          {/* Assigned Projects */}
                          <div className="mt-2 text-sm">
                            <span className="font-medium text-bodydark2">
                              Assigned to:{" "}
                            </span>
                            {subproject_ideas && subproject_ideas.length > 0 ? (
                              <span className="text-bodydark2">
                                {subproject_ideas
                                  .map((item) => item.subproject_type_name)
                                  .join(", ")}
                              </span>
                            ) : (
                              <span className="text-bodydark2">
                                No assigned sub-project found
                              </span>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                }
              )}
            </div>
          ) : (
            // Empty State
            <div className="flex flex-col items-center justify-center py-8">
              <div className="mb-3 rounded-full bg-boxdark p-3">
                <FontAwesomeIcon
                  icon="fa-solid fa-note-sticky"
                  className="h-6 w-6 text-bodydark2"
                />
              </div>
              <p className="text-sm text-bodydark2">
                No ideas available to assign
              </p>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="border-t border-stroke px-6 py-4">
          <div className="flex gap-2">
            <button
              onClick={(e) => handleSubmit(e)}
              className="flex w-full items-center justify-center rounded-sm bg-primary px-6 py-2 text-sm font-medium text-white hover:bg-opacity-90"
            >
              Save Changes
            </button>
            <button
              onClick={() => setModalClose(false)}
              className="flex w-full items-center justify-center rounded-sm bg-danger px-6 py-2 text-sm font-medium text-white hover:bg-opacity-90"
            >
              Cancel
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AssignIdea;
