"use client";

import { useEffect, useState } from "react";
import { clearAuthCookies } from "@/lib/session";
import Link from "next/link";

export default function LoggedOut() {
  const [sessionStatus, setSessionStatus] = useState<'checking' | 'cleared' | 'error'>('checking');
  
  // Clear auth cookies again on this page as an extra precaution
  useEffect(() => {
    const checkAndClearSessions = async () => {
      try {
        // Additional browser storage clearing
        console.log('Performing complete browser storage cleanup');
        
        // Clear cookies
        clearAuthCookies();
        
        // Clear session storage
        try {
          sessionStorage.clear();
          console.log('Session storage cleared');
        } catch (e) {
          console.error('Error clearing session storage:', e);
        }
        
        // Clear local storage items related to auth
        try {
          const authLocalStoragePrefixes = ['token', 'auth', 'session', 'keycloak', 'kc', 'oidc', 'user'];
          
          for (let i = 0; i < localStorage.length; i++) {
            const key = localStorage.key(i);
            if (key) {
              const keyLower = key.toLowerCase();
              if (authLocalStoragePrefixes.some(prefix => keyLower.includes(prefix))) {
                console.log(`Clearing localStorage: ${key}`);
                localStorage.removeItem(key);
              }
            }
          }
          console.log('Local storage auth items cleared');
        } catch (e) {
          console.error('Error clearing localStorage:', e);
        }
        
        // Double check for Keycloak specific cookies
        const keycloakCookies = ['KEYCLOAK_SESSION', 'KEYCLOAK_IDENTITY', 'KC_RESTART'];
        for (const cookieName of keycloakCookies) {
          document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=${window.location.hostname}; SameSite=None; Secure;`;
          document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
        }
        
        setSessionStatus('cleared');
      } catch (error) {
        console.error('Error during session cleanup:', error);
        setSessionStatus('error');
      }
    };
    
    checkAndClearSessions();
  }, []);

  return (
    <div 
      className="min-h-screen flex items-center justify-center"
      style={{
        backgroundImage: "url('/signin.jpg')",
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat'
      }}
    >
      <div className="w-full max-w-md p-8 bg-black/60 backdrop-blur-sm rounded-lg shadow-xl">
        <div className="text-center">
          <h2 className="text-3xl font-bold text-white mb-4">
            You have been logged out
          </h2>
          
          {sessionStatus === 'checking' && (
            <p className="text-white/80 mb-4">
              Verifying all sessions are terminated...
            </p>
          )}
          
          {sessionStatus === 'cleared' && (
            <p className="text-white/80 mb-4">
              Your session has been completely terminated and all authentication data has been cleared.
            </p>
          )}
          
          {sessionStatus === 'error' && (
            <p className="text-white/80 mb-4">
              Your session has been terminated, but there might be some residual session data.
              For complete security, please close your browser.
            </p>
          )}
          
          <div className="mt-6">
            <Link 
              href="/signin"
              className="inline-block px-8 py-3 bg-white text-gray-800 rounded hover:bg-gray-100 transition-colors mb-4"
            >
              Sign In Again
            </Link>
            
            <p className="text-white/60 text-sm mt-4">
              Note: If you're automatically signed in again, try clearing your browser cookies or restarting your browser.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
} 