"use client";

import { useEffect, useState, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { ShieldCheck, AlertCircle } from "lucide-react";
import { fetchWithAuthCore } from "@/lib/api/auth";
import { loginStart, loginSuccess, loginFailure } from "@/lib/store/slices/auth-slice";
import { useAppDispatch } from "@/hooks/use-redux";

function AuthCallbackContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const dispatch = useAppDispatch();
  // Redux auth state is managed through dispatch actions
  const [status, setStatus] = useState<"loading" | "success" | "error">("loading");
  const [message, setMessage] = useState("");

  useEffect(() => {
    const handleCallback = async () => {
      try {
        // Start loading state
        dispatch(loginStart());

        const code = searchParams.get("token");
        const refreshToken = searchParams.get("refresh_token");
        const state = searchParams.get("state");
        const error = searchParams.get("error");

        if (error) {
          dispatch(loginFailure(`Authentication failed: ${error}`));
          setStatus("error");
          setMessage(`Authentication failed: ${error}`);
          return;
        }

        if (!code) {
          dispatch(loginFailure("No authorization code received"));
          setStatus("error");
          setMessage("No authorization code received");
          return;
        }

        // Store tokens in localStorage and cookies
        localStorage.setItem("token", code);
        localStorage.setItem("ksso_refresh_token", refreshToken || "");

        // Set HTTP-only cookie for middleware
        document.cookie = `token=${code}; path=/; secure; samesite=strict`;
        if (refreshToken) {
          document.cookie = `ksso_refresh_token=${refreshToken}; path=/; secure; samesite=strict`;
        }

        // Fetch user data
        const fetchDataUser = await fetchWithAuthCore("/api/users/me", {
          headers: {
            Authorization: `Bearer ${code}`,
          },
        });

        if (!fetchDataUser.ok) {
          const errorData = await fetchDataUser.json();
          const errorMessage = errorData.message || "Failed to fetch user data";
          dispatch(loginFailure(errorMessage));
          throw new Error(errorMessage);
        }

        const userData = await fetchDataUser.json();

        // Store user data in localStorage for persistence
        localStorage.setItem("user_data", JSON.stringify(userData));

        // Dispatch successful login with user data and tokens
        dispatch(
          loginSuccess({
            user: userData,
            accessToken: code,
            refreshToken: refreshToken || undefined,
          }),
        );

        setStatus("success");
        setMessage("Authentication successful! Redirecting...");

        // Redirect after a short delay
        setTimeout(() => {
          // Check for redirect parameter in URL or decode state parameter
          const urlParams = new URLSearchParams(window.location.search);
          const redirectParam = urlParams.get("redirect");
          let redirectTo = "/dashboard"; // Default fallback

          if (redirectParam) {
            redirectTo = redirectParam;
          } else if (state && state !== "dashboard") {
            // Decode state parameter which might contain the redirect path
            try {
              redirectTo = decodeURIComponent(state);
            } catch {
              redirectTo = "/dashboard";
            }
          }

          router.push(redirectTo);
        }, 2000);
      } catch (error) {
        const errorMessage = "An unexpected error occurred during authentication";
        dispatch(loginFailure(errorMessage));
        setStatus("error");
        setMessage(errorMessage);
        console.error("Auth callback error:", error);
      }
    };

    handleCallback();
  }, [searchParams, router, dispatch]);

  return (
    <div className="mx-auto flex w-xs flex-col justify-center space-y-8">
      <div className="space-y-2 text-center">
        <div className="mb-4 flex items-center justify-center">
          <div className="bg-primary text-primary-foreground flex aspect-square size-12 items-center justify-center rounded-lg">
            <ShieldCheck className="size-6" />
          </div>
        </div>
        <h1 className="text-2xl font-bold">
          {status === "loading" && "Authenticating..."}
          {status === "success" && "Welcome Back!"}
          {status === "error" && "Authentication Failed"}
        </h1>
        <p className="text-muted-foreground text-sm text-balance">
          {status === "loading" && "Processing your authentication..."}
          {status === "success" && message}
          {status === "error" && "Please try again or contact support"}
        </p>
      </div>

      <div className="flex justify-center">
        {status === "loading" && (
          <div className="border-primary h-8 w-8 animate-spin rounded-full border-2 border-t-transparent"></div>
        )}

        {status === "success" && (
          <div className="flex h-12 w-12 items-center justify-center rounded-full bg-green-500">
            <ShieldCheck className="h-6 w-6 text-white" />
          </div>
        )}

        {status === "error" && (
          <Alert variant="destructive" className="w-full">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>{message}</AlertDescription>
          </Alert>
        )}
      </div>
    </div>
  );
}

export default function AuthCallbackPage() {
  return (
    <Suspense
      fallback={
        <div className="mx-auto flex w-xs flex-col justify-center space-y-8">
          <div className="space-y-2 text-center">
            <div className="mb-4 flex items-center justify-center">
              <div className="bg-primary text-primary-foreground flex aspect-square size-12 items-center justify-center rounded-lg">
                <ShieldCheck className="size-6" />
              </div>
            </div>
            <h1 className="text-2xl font-bold">Loading...</h1>
            <p className="text-muted-foreground text-sm text-balance">Preparing authentication...</p>
          </div>
          <div className="flex justify-center">
            <div className="border-primary h-8 w-8 animate-spin rounded-full border-2 border-t-transparent"></div>
          </div>
        </div>
      }
    >
      <AuthCallbackContent />
    </Suspense>
  );
}
