"use client";

import { useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { getSupabaseClient } from "@/lib/supabase";

export default function AuthCallbackClient() {
  const router = useRouter();
  const searchParams = useSearchParams();

  useEffect(() => {
    const url = typeof window !== "undefined" ? new URL(window.location.href) : null;
    const hash = url?.hash || "";
    const next = url?.searchParams.get("next") || "/reset-password";
    const code = url?.searchParams.get("code");
    const tokenHashFromQuery = url?.searchParams.get("token_hash");
    const typeFromQuery = url?.searchParams.get("type");

    const params = new URLSearchParams(hash.startsWith("#") ? hash.slice(1) : hash);
    const tokenHashFromHash = params.get("token_hash");
    const typeFromHash = params.get("type");
    const access_token = params.get("access_token");
    const refresh_token = params.get("refresh_token");
    const error = params.get("error") || url?.searchParams.get("error");
    const error_code = params.get("error_code") || url?.searchParams.get("error_code");
    const error_description = params.get("error_description") || url?.searchParams.get("error_description");
    const token_hash = tokenHashFromQuery || tokenHashFromHash;
    const type = typeFromQuery || typeFromHash;

    async function run() {
      if (error || error_code) {
        const redirectParams = new URLSearchParams();
        if (error) redirectParams.set("error", error);
        if (error_code) redirectParams.set("error_code", error_code);
        if (error_description) redirectParams.set("error_description", error_description);
        router.replace(`/reset-password?${redirectParams.toString()}`);
        return;
      }

      if (token_hash && type === "recovery") {
        const redirectParams = new URLSearchParams();
        redirectParams.set("token_hash", token_hash);
        redirectParams.set("type", type);
        router.replace(`/reset-password?${redirectParams.toString()}`);
        return;
      }

      if (code) {
        const supabase = getSupabaseClient();
        const { error: exchangeError } = await supabase.auth.exchangeCodeForSession(code);
        if (!exchangeError) {
          router.replace(next);
          return;
        }

        const redirectParams = new URLSearchParams();
        redirectParams.set("error", "access_denied");
        const message = exchangeError.message || "";
        if (message.toLowerCase().includes("pkce code verifier")) {
          redirectParams.set("error_code", "pkce_verifier_missing");
          redirectParams.set(
            "error_description",
            "Nao foi possivel validar este link neste navegador. Solicite um novo link de recuperacao."
          );
        } else if (message) {
          redirectParams.set("error_description", message);
        }
        router.replace(`/reset-password?${redirectParams.toString()}`);
        return;
      }

      if (access_token && refresh_token) {
        const supabase = getSupabaseClient();
        await supabase.auth.setSession({
          access_token,
          refresh_token,
        });
        router.replace(next);
        return;
      }

      router.replace(`/reset-password${hash || ""}`);
    }

    run();
  }, [router, searchParams]);

  return null;
}
