import { useEffect, useRef, useState } from "react";
import NuevaCoord from "./NuevaCoord";
import EditarIcon from "./EditarIcon";
import ShareIcon from "./ShareIcon";
import RemoveIcon from "./RemoveIcon";
import StaticModal from "./StaticModal";
import EditarModal from "./EditarModal";
import TimedToast from "./TimedToast";

function Modall({ show, CloseModal, Coord, Coords, EliminarCoord, tipo }) {
  if (show === true && Coord !== null) {
    return (
      <StaticModal
        CloseModal={CloseModal}
        Coord={Coord}
        EliminarCoord={() => {
          const nuevasCoords = Coords.filter((c) => c !== Coord);
          localStorage.setItem(tipo, JSON.stringify(nuevasCoords));
          EliminarCoord(nuevasCoords);
        }}
      />
    );
  }
  return null;
}

export default function Keeper({ tipo }) {
  const [coords, setCoords] = useState(
    JSON.parse(localStorage.getItem(tipo) || "[]"),
  );

  const collapseRef = useRef(null);
  const [showModal, setModal] = useState(false);
  const [showEditar, setEditar] = useState(false);
  const [showToast, setShowToast] = useState(false);
  const [selCoord, setCoord] = useState(null);

  useEffect(() => {
    const storedCoords = JSON.parse(localStorage.getItem(tipo) || "[]");

    console.log(storedCoords);
    if (storedCoords) {
      setCoords(storedCoords);
    }
  }, [tipo]);

  const Editar = (coord) => {
    setCoord(coord);
    setEditar(true);
  };

  const Compartir = (coord) => {
    setCoord(coord);
    const textToCopy = `- ${coord.descripcion}, X: ${coord.x}${coord.y ? ` Y: ${coord.y}` : ""} Z: ${coord.z}`;
    navigator.clipboard.writeText(textToCopy);
    setShowToast(true);
  };

  const Remover = (coord) => {
    setCoord(coord);
    setModal(true);
  };
  const collapseAccordion = () => {
    if (collapseRef.current) {
      const bsCollapse = new window.bootstrap.Collapse(collapseRef.current, {
        toggle: false,
      });
      bsCollapse.hide();
    }
  };
  return (
    <>
      <Modall
        show={showModal}
        CloseModal={() => setModal(false)}
        Coord={selCoord}
        Coords={coords}
        EliminarCoord={setCoords}
        tipo={tipo}
      />

      <EditarModal
        show={showEditar}
        close={() => setEditar(false)}
        tipo={tipo}
        coord={selCoord}
        setCoords={setCoords}
      />

      <TimedToast
        durationMs={5000}
        setShow={setShowToast}
        show={showToast}
        message={`Copiada Coordenada [${selCoord?.descripcion}]`}
      />

      <div className="accordion" id="accordionNuevaCoord">
        <div className="accordion-item">
          <h2 className="accordion-header" id="headingNuevaCoord">
            <button
              className="accordion-button collapsed"
              type="button"
              data-bs-toggle="collapse"
              data-bs-target="#collapseNuevaCoord"
              aria-expanded="false"
              aria-controls="collapseNuevaCoord"
            >
              Nueva Coordenada
            </button>
          </h2>

          <div
            id="collapseNuevaCoord"
            className="accordion-collapse collapse"
            aria-labelledby="headingNuevaCoord"
            data-bs-parent="#accordionNuevaCoord"
            ref={collapseRef}
          >
            <div className="accordion-body">
              <NuevaCoord
                coord={coords}
                setcoord={setCoords}
                colapsar={collapseAccordion}
                tipo={tipo}
              />
            </div>
          </div>
        </div>
      </div>
      <hr />

      {coords.length == 0 && (
        <h2 className="list-group-item text-center">
          No hay Coordenadas que Mostrar.
        </h2>
      )}

      <table class="table table-hover table-striped">
        <thead>
          <tr>
            <th>#</th>
            <th>X:</th>
            <th>Y:</th>
            <th>Z:</th>
            <th>Descripcion</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {coords.length != 0 &&
            coords.map((x) => (
              <tr>
                <td>
                  <b>{x.num}</b>
                </td>

                <td>{x.x}</td>
                <td>{x.y !== null && `Y: ${x.y}`}</td>
                <td>{x.z}</td>
                <td>{x.descripcion}</td>
                <td>
                  <button
                    class="ms-2  btn btn-outline-warning btn-sm"
                    onClick={() => Editar(x)}
                  >
                    <EditarIcon />
                  </button>
                  <button
                    className="btn btn-sm btn-outline-info ms-2"
                    onClick={() => Compartir(x)}
                  >
                    <ShareIcon />
                  </button>
                  <button
                    className="btn btn-sm btn-outline-danger ms-2"
                    onClick={() => Remover(x)}
                  >
                    <RemoveIcon />
                  </button>
                </td>
              </tr>
            ))}
        </tbody>
      </table>
    </>
  );
}
