import { JSXElement, createSignal,onMount,useContext } from "solid-js";

import { EngagementIcon } from "../../Util/Icons";
import { engage } from "../../Util/api";
import { LoginContext } from "../../Context/GlobalState";
import { getEngagementCount } from "../../Util/api";

export default function EngagementButton({
  postId,
}: {
  postId: string;
}): JSXElement {
  const [engagementCount, setEngagementCount] = createSignal(0);
  const login_ctx = useContext(LoginContext)!;

  onMount((): void => {
    void setUp()
  })

  const setUp = async () => {
    const r = await getEngagementCount(postId)
    setEngagementCount(r)
  }

  // Function to handle engagement
  const handleEngagement = async () => {
    try {
      const response = await engage(postId, login_ctx.token()) ;
      if (response.ok) {
        // Update engagement count if the request is successful
        setEngagementCount(await response.json());
      } else {
        console.error("Failed to engage:", response.statusText);
      }
    } catch (error) {
      console.error("Error engaging:", error);
    }
  };

  return (
    <div class="flex p-1">
      <button
        class="rounded-base btn btn-xs hover:border-primary"
        aria-label="Show sign of engagement"
        onClick={handleEngagement} // Call handleEngagement function on button click
      >
        <EngagementIcon />
      </button>
      <span class="text-1xl countdown px-1.5 pt-1.5 text-center">
        <p style={{ "--value": engagementCount() }}></p>
      </span>
    </div>
  );
}
