import { use, useState } from "react";
import { AuthContext } from "../../context/AuthContext";
import { useNavigate } from "react-router-dom";
import { EngagementMakeRecipe } from "../../services/EngagementService";
import { isApiError } from "../../types/api/error";

interface MadeButtonProps {
  id: number;
}

export default function MadeButton({ id }: MadeButtonProps) {
  // CONTEXT
  const { isLoggedIn } = use(AuthContext);
  const navigate = useNavigate();

  const [clicked, setClicked] = useState<boolean>(false);

  const clickHandler = async () => {
    // This button cannot be used if not logged in
    if (!isLoggedIn) {
      await navigate("/v2/web/login");
      return;
    }

    if (!id || clicked) return;

    // Toggle button first, to feel fast
    setClicked(true);

    const result = await EngagementMakeRecipe(id);
    if (isApiError(result)) {
      console.error(result.message);
    }
  }

  return (
    <button
      className={`flex items-center min-w-1/4 justify-center gap-x-1 rounded-lg border ${clicked ? "border-blue-500 text-blue-500" : "border-gray-300 text-gray-800"} px-6 py-3 flex-grow hover:bg-gray-50 hover:border-blue-300 duration-300 cursor-pointer`}
      onClick={() => void clickHandler()}
    >
      <svg
        className="h-6"
        fill="currentColor"
        viewBox="0 -3.84 122.88 122.88"
        version="1.1"
        id="Layer_1"
        xmlns="http://www.w3.org/2000/svg"
        xmlnsXlink="http://www.w3.org/1999/xlink"
        xmlSpace="preserve"
      >
        <g>
          <path
            d="M29.03,100.46l20.79-25.21l9.51,12.13L41,110.69C33.98,119.61,20.99,110.21,29.03,100.46L29.03,100.46z M53.31,43.05 c1.98-6.46,1.07-11.98-6.37-20.18L28.76,1c-2.58-3.03-8.66,1.42-6.12,5.09L37.18,24c2.75,3.34-2.36,7.76-5.2,4.32L16.94,9.8 c-2.8-3.21-8.59,1.03-5.66,4.7c4.24,5.1,10.8,13.43,15.04,18.53c2.94,2.99-1.53,7.42-4.43,3.69L6.96,18.32 c-2.19-2.38-5.77-0.9-6.72,1.88c-1.02,2.97,1.49,5.14,3.2,7.34L20.1,49.06c5.17,5.99,10.95,9.54,17.67,7.53 c1.03-0.31,2.29-0.94,3.64-1.77l44.76,57.78c2.41,3.11,7.06,3.44,10.08,0.93l0.69-0.57c3.4-2.83,3.95-8,1.04-11.34L50.58,47.16 C51.96,45.62,52.97,44.16,53.31,43.05L53.31,43.05z M65.98,55.65l7.37-8.94C63.87,23.21,99-8.11,116.03,6.29 C136.72,23.8,105.97,66,84.36,55.57l-8.73,11.09L65.98,55.65L65.98,55.65z"
          ></path>
        </g>
      </svg>
      Made This!
    </button>

  );
}
