"use client";

import { signIn, useSession } from "next-auth/react";
import { useEffect, useState, useRef } from "react";
import { useRouter, useSearchParams } from "next/navigation";

export default function SignIn() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const searchParams = useSearchParams();
  const [initializationStatus, setInitializationStatus] = useState<string | null>(null);
  const hasAttemptedLogin = useRef(false);
  const isLogoutRedirect = useRef(false);

  // Check if we should force login prompt (after logout)
  useEffect(() => {
    // Check for server-side cookie that marks logout
    const forceLoginCookie = document.cookie
      .split(';')
      .find(c => c.trim().startsWith('force_login_prompt='));
    
    // Check URL parameters for logout flag
    const logoutParam = searchParams.get('logout');
    
    // If logout occurred, mark it and prevent auto-login
    if (forceLoginCookie || logoutParam === 'true') {
      isLogoutRedirect.current = true;
      
      // Clear OAuth parameters from URL if present
      const url = new URL(window.location.href);
      const hasOAuthParams = url.searchParams.has('code') || 
                            url.searchParams.has('state') || 
                            url.searchParams.has('error');
      
      if (hasOAuthParams) {
        url.searchParams.delete('code');
        url.searchParams.delete('state');
        url.searchParams.delete('error');
        url.searchParams.delete('error_description');
        url.searchParams.set('logout', 'true');
        window.history.replaceState({}, '', url.toString());
      }
      
      // Don't auto-trigger login after logout
      return;
    }
  }, [searchParams]);

  useEffect(() => {
    // If user is already authenticated, redirect to home
    if (status === "authenticated" && session?.user) {
      router.push("/");
      return;
    }

    // Don't auto-login if this is a logout redirect or we've already attempted login
    if (isLogoutRedirect.current || hasAttemptedLogin.current) {
      return;
    }

    // Don't auto-login if status is still loading (might be processing OAuth callback)
    if (status === "loading") {
      return;
    }

    // Auto-login for new users (SSO natural flow)
    // Only if not authenticated and not from logout
    if (status === "unauthenticated") {
      hasAttemptedLogin.current = true;
      // Small delay to ensure we're not in a logout redirect flow
      const timer = setTimeout(() => {
        if (status === "unauthenticated" && !isLogoutRedirect.current) {
          // Trigger Keycloak sign-in (SSO will work naturally)
          signIn("keycloak", { callbackUrl: "/" });
        }
      }, 1000);
      
      return () => clearTimeout(timer);
    }
  }, [status, session, router]);

  useEffect(() => {
    if (session?.user) {
      console.log("Session available, initializing storage");
      
      // Initialize storage using direct API
      const initializeStorage = async () => {
        try {
          setInitializationStatus("initializing");
          const response = await fetch('/api/storage/init', {
            method: 'POST'
          });
          
          if (!response.ok) {
            console.error('Failed to initialize storage:', await response.text());
            setInitializationStatus("failed");
          } else {
            console.log('Storage initialized successfully');
            setInitializationStatus("success");
            
            // Force reload to ensure session is updated
            setTimeout(() => {
              window.location.href = "/";
            }, 1000);
          }
        } catch (error) {
          console.error('Error initializing storage:', error);
          setInitializationStatus("failed");
        }
      };
      
      initializeStorage();
    }
  }, [session]);

  // Show logout message if coming from logout
  const showLogoutMessage = isLogoutRedirect.current || 
                           searchParams.get('logout') === 'true';

  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 space-y-8 bg-white/90 backdrop-blur-sm p-8 rounded-xl shadow-xl">
        <div>
          <h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-gray-900">
            {showLogoutMessage
              ? "Vous avez été déconnecté avec succès. Veuillez vous reconnecter."
              : initializationStatus === "initializing"
              ? "Initialisation de votre espace..."
              : initializationStatus === "success"
              ? "Initialisation réussie, redirection..."
              : initializationStatus === "failed"
              ? "Échec de l'initialisation. Veuillez réessayer."
              : "Redirection vers la page de connexion..."}
          </h2>
            {showLogoutMessage && (
            <div className="mt-4 text-center">
              <button
                onClick={() => {
                  // Clear flags before logging in
                  hasAttemptedLogin.current = false;
                  isLogoutRedirect.current = false;
                  
                  // Use NextAuth signin normally
                  // The force_login_prompt cookie set by mark-logout will be used
                  // to determine if we should add prompt=login
                  // For now, we'll rely on Keycloak's behavior: if SSO session exists
                  // and we want to force login, we need to add prompt=login
                  // Since NextAuth doesn't easily support dynamic prompt, we'll
                  // use a workaround: modify the authorization URL after NextAuth generates it
                  // This is complex, so for now we'll use normal signin
                  // The user will be prompted if SSO session was cleared by end-sso-session
                  signIn("keycloak", { 
                    callbackUrl: "/",
                  });
                }}
                className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                Se connecter
              </button>
            </div>
          )}
          {initializationStatus === "initializing" && (
            <div className="flex justify-center mt-4">
              <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
