"use client";
import { useSearchParams, useRouter } from "next/navigation";
import { useEffect, useState, useRef } from "react";
import { BASE_URL } from "@/constants";

const Login = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const token = searchParams.get("token");
  const hasRun = useRef(false);

  useEffect(() => {
    async function handleLogin() {
      if (!token) return;
      // localStorage.setItem("auth_token", token);

      if (!hasRun.current) {
        const ref = localStorage.getItem("opt_ref");
        const res = await fetch(BASE_URL + "user?ref=" + ref, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });

        if (!res.ok) {
          console.error("Failed to fetch user");
          return;
        }

        const user = await res.json();
        // localStorage.setItem("auth_token", token);

        await fetch("/api/auth/login", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(user),
        }).then(() => {
          window.location.href = "/profile";
        });
        hasRun.current = true;
      }
    }

    handleLogin();
  }, [token, router]);

  return <></>;
};

export default Login;
