"use client";

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

export default function SignIn() {
  const { data: session } = useSession();
  const [initializationStatus, setInitializationStatus] = useState<string | null>(null);

  useEffect(() => {
    // Trigger Keycloak sign-in
    signIn("keycloak", { callbackUrl: "/" });
  }, []);

  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 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">
            {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>
          {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>
  );
}
