import { useParams } from "react-router-dom";
import { useState, useEffect } from "react";
import { getRoom } from "../../api";
import "./Room.scss";
import AddBtn from "../../components/AddBtn/AddBtn";
import { createItem, deleteItem, updateItem } from "../../api/";
import StylizedBtn from "../../components/StylizedBtn/StylizedBtn";
import LoaderSpace from "../../components/LoaderSpace/LoaderSpace";
import { useAuth } from "../../hooks";

export default function Room() {
  const { _user } = useAuth();
  const { id } = useParams();
  const [data, setData] = useState({});
  const [isInForm, setInForm] = useState(false);
  const [isInFormUpdate, setIsInFormUpdate] = useState(false);
  const [formUpdateData, setFormUpdateData] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    setIsLoading(true);

    getRoom(id).then((res) => {
      console.log(res);
      document.title = `Piece - ${res.name}`;
      setData(res);
      setIsLoading(false);
    });
  }, []);

  const handleFormUpdateDataChange = (e, name) => {
    console.log(e.target.value);
    const cpy = { ...formUpdateData };
    cpy[name] =
      name === "purchaseDate"
        ? new Date(e.target.value).toISOString()
        : e.target.value;
    setFormUpdateData(cpy);
  };

  const handleForm = () => {
    setInForm(!isInForm);
  };

  const handleFormUpdate = (item = null) => {
    if (item) {
      const cpy = { ...item };
      delete cpy.createdAt;
      delete cpy.image;
      delete cpy.invoice;
      delete cpy.user;
      delete cpy.updatedAt;
      delete cpy.__v;
      setFormUpdateData(cpy);
    }

    setIsInFormUpdate(!isInFormUpdate);
  };

  const handleDelete = (item) => {
    const confirmation = prompt(
      `Etes-vous sur de vouloir supprimer ${item.brand} ${item.model} ? (oui ou non)`,
      "oui",
    );

    if (!confirmation || confirmation.toLocaleLowerCase() !== "oui") return;

    deleteItem(item._id).then((_) => {
      const cpy = [...data.items];
      const filtered = cpy.filter((e) => e._id !== item._id);
      setData({ ...data, items: filtered });
    });
  };

  const handleSubmitUpdate = () => {
    try {
      updateItem(formUpdateData).then((_) => {
        // TODO: Je ferai une modification unitaire plus tard
        getRoom(id).then((res) => {
          handleFormUpdate();
          setData(res);
        });
      });
    } catch (err) {
      console.log(err);
      handleFormUpdate();
    }
  };

  const handleSubmit = (e) => {
    try {
      const settings = {};
      settings.brand = e.target[0].value;
      settings.model = e.target[1].value;
      settings.price = e.target[2].value;
      settings.purchaseDate = e.target[3].value;
      settings.link = e.target[4].value;
      settings.description = e.target[5].value;
      settings.room = id;
      settings.image = e.target[6].files[0];
      settings.invoice = e.target[7].files[0];

      createItem(settings).then((_) => {
        // Je prefere faire ca que d'actualiser le state[data.items] car
        // l'image ne se charge pas correctement
        window.location.reload();
      });

      handleForm();
    } catch (err) {
      alert("Quelque chose cloche avec le formulaire ...");
      console.log(err);
    }
  };

  return (
    <div id="room-container">
      {data.name ? (
        <div id="room-title-container">
          <span id="room-title">
            <u>{data.name}</u>
          </span>
        </div>
      ) : null}

      {isLoading ? (
        <LoaderSpace isCenterLoader={true} isVisible={isLoading} />
      ) : null}

      {isInForm || isInFormUpdate ? <div id="blur"></div> : null}

      {data.items && data.items.length > 0 ? (
        <div id="items-container">
          {data.items.map((e, i) => (
            <div className="item-container" key={i}>
              <div id="item-actions-container">
                <button
                  onClick={() => {
                    handleDelete({
                      _id: e._id,
                      brand: e.brand,
                      model: e.model,
                    });
                  }}
                  id="item-delete-btn"
                >
                  ×
                </button>

                <button
                  onClick={() => {
                    handleFormUpdate(e);
                  }}
                  id="item-update-btn"
                >
                  ✏️
                </button>
              </div>
              <div className="item-brand-container">
                <a className="item-brand" href={e.link}>
                  {e.brand}
                </a>
              </div>

              <div className="item-model-container">
                <a className="item-model" href={e.link}>
                  {e.model}
                </a>
              </div>

              {e.image ? (
                <div className="item-image-container">
                  <img
                    className="item-image"
                    src={`https://but-3-dev-project-back.onrender.com/api/file/${e.image._id}`}
                    alt="coucou"
                  />
                </div>
              ) : (
                <span className="item-no-img">Pas d'Image</span>
              )}

              <div className="item-description-container">
                Description ➜
                <span className="item-description">&nbsp;{e.description}</span>
              </div>

              <div className="item-price-container">
                Montant ➜<span className="item-price">&nbsp;{e.price}e</span>
              </div>

              <div className="item-buy-date-container">
                Date d'achat ➜
                <span className="item-buy-date">
                  {new Date(e.purchaseDate).toLocaleDateString("FR-fr")}
                </span>
              </div>
            </div>
          ))}
        </div>
      ) : null}

      {isInForm && (
        <div id="form-container">
          <span>Creation d'item</span>

          <div id="form-closure-container">
            <button id="form-closure" onClick={handleForm}>
              ×
            </button>
          </div>

          <form id="form" onSubmit={handleSubmit}>
            <input type="text" placeholder="Marque ..." />
            <input type="text" placeholder="Model ..." />
            <input type="number" placeholder="Prix ..." />
            <input type="date" placeholder="Date d'achat ..." />
            <input type="text" placeholder="Lien ..." />
            <input type="text" placeholder="Description ..." />
            <input type="file" placeholder="Photo ..." />
            <input type="file" placeholder="Facture ..." />

            <div id="actions">
              <button className="actions-btn" onClick={handleForm}>
                Annuler
              </button>
              <button className="actions-btn" type="submit">
                Confirmer
              </button>
            </div>
          </form>
        </div>
      )}

      {isInFormUpdate && (
        <div id="form-update-container">
          <span>
            Modification de{" "}
            <b>
              {formUpdateData.brand} {formUpdateData.model}
            </b>
          </span>

          <div id="form-closure-container">
            <button id="form-closure" onClick={handleFormUpdate}>
              ×
            </button>
          </div>

          <div id="form-update">
            <input
              onChange={(e) => {
                handleFormUpdateDataChange(e, "brand");
              }}
              type="text"
              placeholder={`(Marque) ${formUpdateData.brand}`}
            />
            <input
              onChange={(e) => {
                handleFormUpdateDataChange(e, "model");
              }}
              type="text"
              placeholder={`(Modele) ${formUpdateData.model}`}
            />
            <input
              onChange={(e) => {
                handleFormUpdateDataChange(e, "description");
              }}
              type="text"
              placeholder={`(Description) ${formUpdateData.description}`}
            />
            <input
              onChange={(e) => {
                handleFormUpdateDataChange(e, "price");
              }}
              type="number"
              placeholder={`(Prix) ${formUpdateData.price}`}
            />
            <input
              onChange={(e) => {
                handleFormUpdateDataChange(e, "purchaseDate");
              }}
              type="date"
              min="1900-01-01"
              max="2100-01-01"
              value={`${new Date(formUpdateData.purchaseDate).toISOString().split("T")[0].replace(/-/g, "-")}`}
            />
            <input
              onChange={(e) => {
                handleFormUpdateDataChange(e, "link");
              }}
              type="text"
              placeholder={`(Lien) ${formUpdateData.link}`}
            />

            <div id="actions">
              <StylizedBtn
                perso_style={{ width: "75px" }}
                text={"Annuler"}
                handle={handleFormUpdate}
              />
              <StylizedBtn
                perso_style={{ width: "75px" }}
                text={"Confirmer"}
                handle={handleSubmitUpdate}
              />
            </div>
          </div>
        </div>
      )}

      <AddBtn handle={handleForm} />
    </div>
  );
}
