import { useEffect, useRef, useState } from "react";
import { Navigate, useNavigate, useSearchParams } from "react-router-dom";
import { useSession } from "@xtablo/shared/contexts/SessionContext";

export function AuthCallback() {
  const [searchParams] = useSearchParams();
  const token = searchParams.get("token");
  const { session } = useSession();
  const navigate = useNavigate();
  const [error, setError] = useState<string | null>(null);
  const hasAccepted = useRef(false);

  useEffect(() => {
    if (!token) {
      return;
    }

    if (!session || hasAccepted.current) {
      return;
    }

    hasAccepted.current = true;

    const apiUrl = import.meta.env.VITE_API_URL as string;

    fetch(`${apiUrl}/api/v1/client-invites/accept/${token}`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${session.access_token}`,
        "Content-Type": "application/json",
      },
    })
      .then(async (res) => {
        if (!res.ok) {
          const body = await res.json().catch(() => ({}));
          throw new Error(
            (body as { message?: string }).message ?? "Erreur lors de l'acceptation de l'invitation"
          );
        }
        return res.json() as Promise<{ tabloId: string }>;
      })
      .then((data) => {
        navigate(`/tablo/${data.tabloId}`, { replace: true });
      })
      .catch((err: unknown) => {
        console.error("Accept invite error:", err);
        setError(
          "Une erreur est survenue lors de l'acceptation de l'invitation. Veuillez contacter la personne qui vous a invite."
        );
      });
  }, [session, token, navigate]);

  if (!token) {
    return <Navigate to="/login" replace />;
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <div className="text-center space-y-3 max-w-md px-4">
          <p className="text-lg font-medium text-destructive">Erreur</p>
          <p className="text-sm text-muted-foreground">{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-background">
      <div className="text-center space-y-3">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto" />
        <p className="text-sm text-muted-foreground">Authentification en cours...</p>
      </div>
    </div>
  );
}
