"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(() => {
    // Clear cookies on errors or manual signout
    if (error) {
      console.log("Clearing auth cookies due to error:", error);
      clearAuthCookies();
      
      // Set error message
      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]);

  // Simple login function
  const handleSignIn = () => {
    signIn("keycloak", { callbackUrl: "/" });
  };

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