"use client";

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

import { AuthLayout } from "../components";
import { LoginForm } from "@/features/auth/components";
import { useAuthStore } from "../services/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";

function LoginContent() {
  const { loading, isAuthenticated } = useAuthStore();
  const searchParams = useSearchParams();
  const reasonParam = useMemo(() => searchParams?.get("reason"), [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]);

  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 />
      </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;
