"use client";

import { signIn, useSession } from "next-auth/react";
import { useEffect, useState } 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 [isLoggingIn, setIsLoggingIn] = useState(false);
  
  // Check URL parameters for logout flag
  const logoutParam = searchParams.get('logout');
  const isLogoutRedirect = logoutParam === 'true';

  // Debug logging
  useEffect(() => {
    console.log('[SignIn] Status:', status, 'Session:', !!session, 'Logout redirect:', isLogoutRedirect);
  }, [status, session, isLogoutRedirect]);

  // Clear stale force_login_prompt cookie on mount (it should only last 5 minutes)
  useEffect(() => {
    // If not a logout redirect, clear any stale force_login_prompt cookie
    if (!isLogoutRedirect) {
      const forceLoginCookie = document.cookie
        .split(';')
        .find(c => c.trim().startsWith('force_login_prompt='));
      
      if (forceLoginCookie) {
        console.log('[SignIn] Clearing stale force_login_prompt cookie');
        document.cookie = 'force_login_prompt=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC';
      }
    }
  }, [isLogoutRedirect]);

  // Handle authentication redirect
  useEffect(() => {
    // If user is already authenticated, redirect to home
    if (status === "authenticated" && session?.user) {
      console.log('[SignIn] User authenticated, redirecting to home');
      router.push("/");
      return;
    }

    // Auto-login disabled - user must click the button to connect
    // This allows users to see and appreciate the sign-in page
  }, [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]);

  return (
    <div 
      className="min-h-screen flex flex-col"
      style={{
        backgroundImage: "url('/SignIn.jpg')",
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat'
      }}
    >
      {/* Header with login button in top right */}
      <header className="w-full flex justify-end p-6">
        {status === "unauthenticated" && !isLoggingIn && (
          <button
            onClick={() => {
              console.log('[SignIn] Login button clicked');
              setIsLoggingIn(true);
              signIn("keycloak", { callbackUrl: "/" });
            }}
            className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-semibold shadow-lg hover:shadow-xl"
          >
            Se connecter
          </button>
        )}
      </header>

      {/* Main content centered */}
      <div className="flex-1 flex items-center justify-center">
        <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">
              {isLogoutRedirect
                ? "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."
                : isLoggingIn
                ? "Connexion en cours..."
                : status === "loading"
                ? "Chargement..."
                : ""}
            </h2>
            
            {(initializationStatus === "initializing" || isLoggingIn || status === "loading") && (
              <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>
    </div>
  );
}
