import "./styles.css";

import parse from "html-react-parser";
import { render } from "react-dom";
import { useEffect, useState } from "react";

import Container from "../../layouts/Container/index.js";
import allData from "../../data/dataFiltered.js";

const Admin = () => {
  const [data, setData] = useState();

  useEffect(() => {
    const filterDataByFolder = (folderId) => {
      const filteredData = allData.filter((item) => item.folder === folderId);

      return filteredData.map((item) => {
        const subItems = filterDataByFolder(item._id);
        return {
          ...item,
          subItems,
        };
      });
    };

    const mainFolders = allData.filter((item) => item.folder === null);
    const filteredData = mainFolders.map((item) => {
      const subItems = filterDataByFolder(item._id);
      return {
        ...item,
        subItems,
      };
    });

    setData(filteredData);
  }, [setData]);

  let trash = [];
  const addToTrash = (itemId) => (e) => {
    trash.push(itemId);
    e.target.parentNode.style.backgroundColor = "green";
  };
  const recoverFromTrash = (itemId) => (e) => {
    trash = trash.filter((item) => item._id !== itemId);
    e.target.parentNode.style.backgroundColor = "white";
  };

  const createNewJSON = () => {
    const newJSON = allData.filter((item) => !trash.includes(item._id));
    console.log(newJSON);
  };

  const showTrash = () => {
    console.log(trash);
  };

  const changeObjectName = (itemId) => (e) => {
    console.log(itemId);
    console.log(e.target.parentNode.querySelector("input").value);
    let newName = e.target.parentNode.querySelector("input").value;
    allData.map((item) => {
      if (item._id === itemId) {
        item.name = newName;
      }
    });
    console.log(allData.filter((item) => item._id === itemId)); // check if the name has been changed
  };

  const changeObjectDescription = (itemId) => (e) => {
    console.log(itemId);
    console.log(e.target.parentNode.querySelector("textarea").value);
    let newDesc = e.target.parentNode.querySelector("textarea").value;
    // allData.map((item) => {
    //   if (item._id === itemId) {
    //     item.system.description.value = newDesc;
    //   }
    // });
    // console.log(allData.filter((item) => item._id === itemId)); // check if the name has been changed
  };

  const renderSubItems = (subItems) => {
    if (subItems?.length === 0) {
      return subItems?.length !== 0 ? (
        <div>
          <img src={subItems.img} alt="noIMG" />
          <div>
            <h4>
              {subItems?._id} - {subItems?.name}
            </h4>
            <h6>Change name</h6>
            <input type="text" />
            <button onClick={changeObjectName(subItems?._id)}>Valider</button>
          </div>
          <button onClick={recoverFromTrash(subItems?._id)}>Recover</button>
          <button onClick={addToTrash(subItems?._id)}>Delete</button>
        </div>
      ) : (
        <></>
      );
    } else {
      return subItems?.map((subItem, subId) => {
        return (
          <div key={`subItem-${subId}`}>
            {subItems?.length !== 0 ? (
              <div
                style={{
                  color: "green",
                  display: "flex",
                  justifyContent: "space-between",
                }}
              >
                <img src={subItem.img} alt="noIMG" />
                <div style={{ maxWidth: "20%" }}>
                  <h5
                    className={
                      subItem?._key === `!folders!${subItem?._id}`
                        ? "selected"
                        : ""
                    }
                  >
                    <i>{subItem?._id}</i> - {subItem?.name}
                  </h5>

                  <h6>Change name</h6>
                  <input type="text" />
                  <button onClick={changeObjectName(subItem?._id)}>
                    Valider
                  </button>
                </div>
                <div style={{ maxWidth: "20%" }}>
                  {subItem.system && parse(subItem.system.description.value)}
                  <h6>Change description</h6>

                  <textarea id={subItem._id} name="desc" rows="5" cols="33" />
                  <button onClick={changeObjectDescription(subItem?._id)}>
                    Valider
                  </button>
                </div>

                <button onClick={recoverFromTrash(subItem?._id)}>
                  Recover
                </button>
                <button onClick={addToTrash(subItem?._id)}>Delete</button>
              </div>
            ) : (
              <></>
            )}
            {renderSubItems(subItem?.subItems)}
          </div>
        );
      });
    }
  };

  return (
    <div className="admin">
      <Container>
        {data?.map((item, id) => (
          <div key={`top-${id}`}>
            <div>
              <img src={item.img} alt="noIMG" />
              <h3>
                {item?._id} - {item?.name}
              </h3>
              <button onClick={recoverFromTrash(item._id)}>Recover</button>
              <button onClick={addToTrash(item._id)}>Delete</button>
            </div>
            {renderSubItems(item?.subItems)}
          </div>
        ))}
        <button onClick={createNewJSON}>Valider</button>
        <button onClick={showTrash}>Afficher corbeille</button>
      </Container>
    </div>
  );
};

// {
//   _id: "kLHR7GDjdqHOA4bl",
//   name: "Billes explosives",
//   type: "consumable",
//   img: "/icons/magic/fire/explosion-fireball-small-orange.webp",
//   folder: "e2iHmimKcOR3YCha",
//     description: "<p><span style="font-size:13px;font-family:Arial;text-decoration-skip-ink:none">Le shinobi peut créer un sac de billes explosives. Au début, elle ne contient qu'une seule bille, mais si ce gadget est séléctionné a plus haut niveau, il multiple les dégats finaux.</span></p>\n<p><span style="font-size:13px;font-family:Arial;text-decoration-skip-ink:none">Le shinobi défait un sac de bille sur son adversaire qui prends des explosions de plein fouet.</span></p>\n<p>Chaque bille inflige 1d8+INT dégat de feu.</p>",
//     source: "",
//     quantity: 1,
//     weight: 0,
//     price: 0,
//     rarity: "uncommon",
//     activation: { type: "action", cost: 1, condition: "" },
//     duration: { value: null, units: "" },
//     range: { value: null, long: null, units: "" },
//     uses: {
//       value: 1,
//       max: "1",
//       per: "charges",
//       recovery: "",
//       autoDestroy: false,
//     },
//     consume: { type: "", target: "", amount: null },
//     ability: "",
//     actionType: "msak",
//     attackBonus: "0",
//     critical: { threshold: null},
//     damage: { parts: [["1d8+@abilites.int.mod", "fire"]], versatile: "" },
//     formula: "",
//     save: { ability: "", dc: null, scaling: "spell" },
// },

export default Admin;
