import React, { useState, useEffect } from "react";
import { withRouter } from "react-router-dom";
import axios from "axios";

//Queries
import {
  savePost,
  removePost,
  checkPostIsSaved,
} from "../../queries/posts_queries";

//Static files
import "../../public/css/SavePost/savePost.css";

function Save({ postId, user }) {
  const [isSaved, setIsSaved] = useState(false);
  const [postSaved, setPostSaved] = useState({});

  const handleSavePost = async (e) => {
    e.preventDefault();
    const result = await savePost(user._id, postId);
    setPostSaved(result);
    setIsSaved(true);
  };

  const handleRemoveSavedPost = async (e) => {
    e.preventDefault();
    await removePost(postSaved._id);
    setIsSaved(false);
  };

  const handleCheckPostIsSaved = async () => {
    const result = await checkPostIsSaved(postId, user._id);
    if (result) {
      setPostSaved(result);
      setIsSaved(true);
    } else {
      setIsSaved(false);
    }
  };

  useEffect(() => {
    handleCheckPostIsSaved();
  }, [isSaved, postId]);

  return (
    <div className="save-post">
      {isSaved ? (
        <svg
          aria-label="Eliminar"
          className="save-post-icon"
          fill="#262626"
          height="24"
          viewBox="0 0 48 48"
          width="24"
          onClick={handleRemoveSavedPost}
        >
          <path d="M43.5 48c-.4 0-.8-.2-1.1-.4L24 28.9 5.6 47.6c-.4.4-1.1.6-1.6.3-.6-.2-1-.8-1-1.4v-45C3 .7 3.7 0 4.5 0h39c.8 0 1.5.7 1.5 1.5v45c0 .6-.4 1.2-.9 1.4-.2.1-.4.1-.6.1z"></path>
        </svg>
      ) : (
        <svg
          aria-label="Guardar"
          className="save-post-icon"
          fill="#262626"
          height="24"
          viewBox="0 0 48 48"
          width="24"
          onClick={handleSavePost}
        >
          <path d="M43.5 48c-.4 0-.8-.2-1.1-.4L24 29 5.6 47.6c-.4.4-1.1.6-1.6.3-.6-.2-1-.8-1-1.4v-45C3 .7 3.7 0 4.5 0h39c.8 0 1.5.7 1.5 1.5v45c0 .6-.4 1.2-.9 1.4-.2.1-.4.1-.6.1zM24 26c.8 0 1.6.3 2.2.9l15.8 16V3H6v39.9l15.8-16c.6-.6 1.4-.9 2.2-.9z"></path>
        </svg>
      )}
    </div>
  );
}

export default withRouter(Save);
