"use client";

import { useEffect, useRef, useState } from "react";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { Button } from "@/components/Button";
import { AuthCard, AuthCardHeader } from "@/components/auth/AuthCard";
import { useAuth } from "@/components/auth/AuthProvider";
import { ApiError, authApi, parseUser } from "@/lib/api";
import { destinationAfterAuth } from "@/lib/auth-destination";

export function CompleteEmailVerificationPage() {
  const router = useRouter();
  const params = useParams<{ id: string; hash: string }>();
  const searchParams = useSearchParams();
  const { user, isLoading, isSessionVerified, setUser, refresh } = useAuth();
  const [loadError, setLoadError] = useState(false);
  const [message, setMessage] = useState("");
  const startedRef = useRef(false);

  useEffect(() => {
    if (isLoading) {
      return;
    }

    if (!isSessionVerified) {
      setLoadError(true);
      return;
    }

    setLoadError(false);

    if (!user) {
      router.replace("/signin");
      return;
    }

    if (startedRef.current) {
      return;
    }

    startedRef.current = true;

    const id = params.id;
    const hash = params.hash;
    const expires = searchParams.get("expires");
    const signature = searchParams.get("signature");

    if (!id || !hash || !expires || !signature) {
      setMessage("This verification link is invalid. Request a new email and try again.");
      return;
    }

    const query = new URLSearchParams({ expires, signature }).toString();

    void (async () => {
      try {
        const response = await authApi.verifyEmail(id, hash, query);
        const nextUser = parseUser(response.user);
        if (nextUser) {
          setUser(nextUser);
          router.replace(destinationAfterAuth(nextUser));
        } else {
          await refresh();
          router.replace("/dashboard");
        }
      } catch (error) {
        if (error instanceof ApiError && error.status === 401) {
          router.replace("/signin");
          return;
        }

        if (error instanceof ApiError && error.kind === "rate_limited") {
          setMessage("Too many attempts. Please wait a moment and try again.");
          return;
        }

        setMessage("This verification link is invalid or has expired. Request a new email and try again.");
      }
    })();
  }, [isLoading, isSessionVerified, user, params.id, params.hash, searchParams, router, setUser, refresh]);

  if (loadError) {
    return (
      <AuthCard>
        <AuthCardHeader eyebrow="Email" title="Couldn’t verify email" />
        <p className="mt-4 text-[0.94rem] text-ink-60">
          Something went wrong while checking your session. Please try again.
        </p>
        <Button className="mt-4 w-full" onClick={() => window.location.reload()}>
          Try again
        </Button>
      </AuthCard>
    );
  }

  if (message) {
    return (
      <AuthCard>
        <AuthCardHeader eyebrow="Email" title="Verify your email" />
        <p
          className="mt-4 rounded-pv border border-accent/30 bg-accent/5 px-3 py-2.5 text-[0.88rem] text-accent"
          role="alert"
        >
          {message}
        </p>
        <Button className="mt-4 w-full" href="/verify-email">
          Back to verification
        </Button>
      </AuthCard>
    );
  }

  return (
    <div className="my-auto py-4" role="status" aria-live="polite">
      <p className="text-center text-[0.95rem] font-medium text-ink-60">Verifying your email…</p>
    </div>
  );
}
