"use client";

import { Suspense, useEffect, useMemo, useRef, useState } from "react";
import { useSearchParams } from "next/navigation";

import { AuthLayout } from "../components";
import { LoginForm } from "@/features/auth/components";
import { useAuthStore } from "../stores/auth.store";
import { LoadingOverlay } from "@/components/atoms";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import {
  consumeLogoutReason,
  isLogoutReason,
  resolveLogoutMessage,
  type LogoutReason,
} from "@/features/auth/utils/logout-reason";
import { getPostLoginRedirect } from "@/features/auth/utils/route-protection";

function LoginContent() {
  const { loading, isAuthenticated } = useAuthStore();
  const searchParams = useSearchParams();
  const reasonParam = useMemo(() => searchParams?.get("reason"), [searchParams]);
  const prefillEmail = useMemo(() => searchParams?.get("email") ?? undefined, [searchParams]);
  const [logoutReason, setLogoutReason] = useState<LogoutReason | null>(null);
  const [dismissed, setDismissed] = useState(false);

  useEffect(() => {
    if (isLogoutReason(reasonParam)) {
      setLogoutReason(reasonParam);
      return;
    }

    const stored = consumeLogoutReason();
    if (stored) {
      setLogoutReason(stored);
    } else {
      setLogoutReason(null);
    }
  }, [reasonParam]);

  useEffect(() => {
    if (logoutReason) {
      setDismissed(false);
    }
  }, [logoutReason]);

  // Track if redirect has been initiated to prevent multiple attempts
  const hasRedirected = useRef(false);

  // Redirect authenticated users away from login page
  useEffect(() => {
    if (isAuthenticated && !loading && !hasRedirected.current) {
      hasRedirected.current = true;
      const redirectTo = searchParams ? getPostLoginRedirect(searchParams) : "/account";
      // Force hard navigation - auth state is persisted via cookies
      window.location.assign(redirectTo);
    }
  }, [isAuthenticated, loading, searchParams]);

  const logoutMessage = logoutReason ? resolveLogoutMessage(logoutReason) : null;

  return (
    <>
      <AuthLayout title="Welcome back" subtitle="Sign in to your Assist Solutions account">
        {logoutMessage && !dismissed && (
          <AlertBanner
            variant={logoutMessage.variant}
            title={logoutMessage.title}
            className="mb-4"
            onClose={() => setDismissed(true)}
          >
            {logoutMessage.body}
          </AlertBanner>
        )}
        <LoginForm initialEmail={prefillEmail} />
      </AuthLayout>

      {/* Full-page loading overlay during authentication */}
      <LoadingOverlay
        isVisible={loading && isAuthenticated}
        title="Redirecting to dashboard..."
        subtitle="Please wait while we load your account"
      />
    </>
  );
}

export function LoginView() {
  return (
    <Suspense
      fallback={
        <AuthLayout title="Welcome back" subtitle="Sign in to your Assist Solutions account">
          <div className="space-y-4 animate-pulse">
            <div className="h-10 rounded bg-gray-200" />
            <div className="h-10 rounded bg-gray-200" />
            <div className="h-10 rounded bg-gray-200" />
          </div>
        </AuthLayout>
      }
    >
      <LoginContent />
    </Suspense>
  );
}

export default LoginView;
