"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Button } from "@/components/Button";
import { AuthCard, AuthCardFooter, 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 VerifyEmailPage() {
  const router = useRouter();
  const { user, isLoading, isSessionVerified, setUser, refresh, logout } = useAuth();
  const [loadError, setLoadError] = useState(false);
  const [isLoggingOut, setIsLoggingOut] = useState(false);
  const [status, setStatus] = useState<"idle" | "sending">("idle");

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

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

    setLoadError(false);

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

    if (user.email_verified) {
      router.replace(destinationAfterAuth(user));
    }
  }, [isLoading, isSessionVerified, user, router]);

  async function handleResend() {
    if (status === "sending" || !user) {
      return;
    }

    setStatus("sending");

    try {
      const response = await authApi.resendVerification();
      const nextUser = parseUser(response.user);
      if (nextUser) {
        setUser(nextUser);
      } else {
        await refresh();
      }
      toast.success(response.message || "Verification email sent.");
    } catch (error) {
      if (error instanceof ApiError && error.kind === "rate_limited") {
        toast.error("Please wait a moment before requesting another email.");
        return;
      }
      toast.error("Couldn’t send the verification email. Please try again.");
    } finally {
      setStatus("idle");
    }
  }

  async function handleLogout() {
    if (isLoggingOut) {
      return;
    }

    setIsLoggingOut(true);

    try {
      await logout();
    } finally {
      router.replace("/signin");
    }
  }

  if (loadError) {
    return (
      <AuthCard>
        <AuthCardHeader eyebrow="Email" title="Couldn’t load this page" />
        <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 (!isSessionVerified || isLoading || !user || user.email_verified) {
    return (
      <div className="my-auto py-4" role="status" aria-live="polite">
        <p className="text-center text-[0.95rem] font-medium text-ink-60">
          {isSessionVerified && !user
            ? "Redirecting to sign in…"
            : isSessionVerified && user?.email_verified
              ? "Redirecting to dashboard…"
              : "Loading…"}
        </p>
      </div>
    );
  }

  return (
    <AuthCard>
      <AuthCardHeader eyebrow="Email" title="Verify your email" />
      <p className="mt-4 text-[0.94rem] text-ink-60">
        A verification link has been sent to{" "}
        <span className="font-semibold text-text">{user.email}</span>. Open that email and follow
        the link to continue.
      </p>
      <Button
        type="button"
        className="mt-4 w-full disabled:pointer-events-none disabled:opacity-70"
        disabled={status === "sending"}
        aria-busy={status === "sending"}
        onClick={() => {
          void handleResend();
        }}
      >
        {status === "sending" ? "Sending…" : "Resend verification email"}
      </Button>
      <AuthCardFooter>
        Wrong account?{" "}
        <button
          type="button"
          className="font-semibold text-primary hover:text-accent disabled:opacity-70"
          onClick={() => {
            void handleLogout();
          }}
          disabled={isLoggingOut}
        >
          {isLoggingOut ? "Signing out…" : "Sign out"}
        </button>
      </AuthCardFooter>
    </AuthCard>
  );
}
