"use client";

import { signIn, useSession } from "next-auth/react";
import { useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import { clearAuthCookies } from "@/lib/session";

export default function SignIn() {
  const { data: session } = useSession();
  const searchParams = useSearchParams();
  const signedOut = searchParams.get('signedOut') === 'true';
  const [isRedirecting, setIsRedirecting] = useState(false);
  const [isFromLogout, setIsFromLogout] = useState(false);

  // If signedOut is true, make sure we clean up any residual sessions
  useEffect(() => {
    if (signedOut) {
      console.log('User explicitly signed out, clearing any residual session data');
      clearAuthCookies();
    }
  }, [signedOut]);

  // Check if we came from the loggedout page
  useEffect(() => {
    const referrer = document.referrer;
    const isFromLoggedOutPage = referrer && 
      (referrer.includes('/loggedout') || referrer.includes('/signout'));
    
    if (isFromLoggedOutPage) {
      console.log('Detected navigation from logout page, preventing auto-login');
      setIsFromLogout(true);
    }
  }, []);

  useEffect(() => {
    // Only automatically sign in if not explicitly signed out and not coming from logout
    if (!signedOut && !isFromLogout && !isRedirecting && !session) {
      setIsRedirecting(true);
      console.log('Triggering automatic sign-in');
      // Add a small delay to avoid immediate redirect which can cause loops
      const timer = setTimeout(() => {
        // Trigger Keycloak sign-in
        signIn("keycloak", { callbackUrl: "/" });
      }, 500);
      
      return () => clearTimeout(timer);
    }
  }, [signedOut, isRedirecting, isFromLogout, session]);

  useEffect(() => {
    if (session?.user && !session.user.nextcloudInitialized) {
      // Initialize Nextcloud
      fetch('/api/nextcloud/init', {
        method: 'POST'
      }).then(response => {
        if (!response.ok) {
          console.error('Failed to initialize Nextcloud');
        }
      }).catch(error => {
        console.error('Error initializing Nextcloud:', error);
      });
    }
  }, [session]);

  const showManualLoginButton = signedOut || isFromLogout || isRedirecting;

  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-6">
            {signedOut ? 'You have signed out' : 'Welcome Back'}
          </h2>
          
          {isRedirecting && !showManualLoginButton && (
            <p className="text-white/80 mb-4">
              Redirecting to login...
            </p>
          )}
          
          {showManualLoginButton ? (
            <button
              onClick={() => signIn("keycloak", { callbackUrl: "/" })}
              className="w-full bg-white text-gray-800 py-3 rounded hover:bg-gray-100 transition-colors"
            >
              Sign In
            </button>
          ) : (
            <div className="flex items-center justify-center">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-white"></div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
