"use client";

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

export default function SignIn() {
  const searchParams = useSearchParams();
  const error = searchParams.get("error");
  const [message, setMessage] = useState("");
  
  useEffect(() => {
    // Always clear cookies on signin page load to ensure fresh authentication
    clearAuthCookies();
    
    // Set error message if present
    if (error) {
      console.log("Clearing auth cookies due to error:", error);
      
      if (error === "RefreshTokenError" || error === "invalid_grant") {
        setMessage("Your session has expired. Please sign in again.");
      } else {
        setMessage("There was a problem with authentication. Please sign in.");
      }
    }
  }, [error]);

  // Login function with callbackUrl to maintain original destination
  const handleSignIn = () => {
    // Get the callback URL from the query parameters or use the home page
    const callbackUrl = searchParams.get("callbackUrl") || "/";
    
    // Add a timestamp parameter to avoid caching issues
    const timestamp = new Date().getTime();
    const authParams = {
      callbackUrl,
      redirect: true,
      // Adding a timestamp to force Keycloak to skip any cached session
      authParams: { 
        prompt: "login",
        t: timestamp.toString()
      }
    };
    
    signIn("keycloak", authParams);
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-100">
      <div className="max-w-md w-full p-8 bg-white rounded-lg shadow-lg">
        <h1 className="text-2xl font-bold text-center mb-6">Sign In</h1>
        
        {message && (
          <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
            {message}
          </div>
        )}
        
        <button
          onClick={handleSignIn}
          className="w-full bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded"
        >
          Sign in with Keycloak
        </button>
      </div>
    </div>
  );
}
