"use client";

import { useEffect } from "react";
import { useSession } from "next-auth/react";
import { clearAuthCookies } from "@/lib/session";

export function SignOutHandler() {
  const { data: session } = useSession();

  useEffect(() => {
    const handleSignOut = async () => {
      try {
        // First, clear all auth-related cookies to ensure we break any local sessions
        clearAuthCookies();
        
        // Create a temporary HTML form for direct POST logout (more reliable than redirect)
        if (process.env.NEXT_PUBLIC_KEYCLOAK_ISSUER && session?.accessToken) {
          console.log('Directly calling Keycloak logout endpoint');
          
          // Create a hidden form for POST logout
          const form = document.createElement('form');
          form.method = 'POST';
          form.action = `${process.env.NEXT_PUBLIC_KEYCLOAK_ISSUER}/protocol/openid-connect/logout`;
          
          // Add the id_token_hint
          if (session.accessToken) {
            const tokenInput = document.createElement('input');
            tokenInput.type = 'hidden';
            tokenInput.name = 'id_token_hint';
            tokenInput.value = session.accessToken;
            form.appendChild(tokenInput);
          }
          
          // Add post_logout_redirect_uri pointing to a special loggedout page
          const redirectInput = document.createElement('input');
          redirectInput.type = 'hidden';
          redirectInput.name = 'post_logout_redirect_uri';
          redirectInput.value = `${window.location.origin}/loggedout`;
          form.appendChild(redirectInput);
          
          // Append to body and submit
          document.body.appendChild(form);
          form.submit();
        } else {
          console.log('No Keycloak configuration found, performing simple redirect');
          // Fallback if no Keycloak config or session
          window.location.href = '/loggedout';
        }
      } catch (error) {
        console.error('Error during logout:', error);
        // Fallback if something goes wrong
        window.location.href = '/loggedout';
      }
    };

    // Add a slight delay to ensure useSession has loaded
    const timer = setTimeout(() => {
      handleSignOut();
    }, 100);
    
    return () => clearTimeout(timer);
  }, [session]);

  return (
    <div className="w-full h-full flex items-center justify-center">
      <div className="text-center">
        <h2 className="text-2xl font-bold">Logging out...</h2>
        <p className="text-gray-500 mt-2">Please wait while we sign you out.</p>
      </div>
    </div>
  );
} 