"use client";

import { Suspense, useCallback, useEffect, useRef, useState } from "react";
import { Alert, Button, Card, Typography } from "antd";
import { useRouter, useSearchParams } from "next/navigation";

import { fetchPlatformBranding } from "@/lib/api/branding";
import { useAuth } from "@/lib/hooks/use-auth";

const { Title, Paragraph, Text } = Typography;

const SSO_PROVIDER = (process.env.NEXT_PUBLIC_SSO_PROVIDER ?? "auth0").toLowerCase();
const PROVIDER_LABEL = SSO_PROVIDER === "google" ? "Google Workspace" : "Auth0";
const LOGIN_CTA = `Continue with ${PROVIDER_LABEL} SSO`;
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1"]);

type LoginNotice = {
  kind: "info" | "warning";
  title: string;
  description: string;
};

type LoginStatus = "idle" | "starting" | "redirecting" | "error";

function LoginContent() {
  const { startSSOLogin, setSession } = useAuth();
  const router = useRouter();
  const params = useSearchParams();
  const [displayName, setDisplayName] = useState("Cloud Security Center");
  const [hostname, setHostname] = useState("");
  const [hasMounted, setHasMounted] = useState(false);
  const [status, setStatus] = useState<LoginStatus>("idle");
  const [loginError, setLoginError] = useState<string | null>(null);
  const [notice, setNotice] = useState<LoginNotice | null>(null);
  const autoLoginAttemptedRef = useRef(false);
  const reason = params?.get("reason");

  const isLocalEnvironment = process.env.NODE_ENV !== "production" || (hasMounted && LOCAL_HOSTS.has(hostname));
  const statusCopy = (() => {
    if (status === "starting") {
      return "Starting sign-in...";
    }
    if (status === "redirecting") {
      return "Redirecting...";
    }
    if (status === "error") {
      return "Sign-in could not start. Check the backend and try again.";
    }
    return isLocalEnvironment
      ? "Local development may sign you in directly."
      : "You will be redirected to your organization's sign-in flow.";
  })();

  const handleLogin = useCallback(async () => {
    setStatus("starting");
    setLoginError(null);

    try {
      const { session, url } = await startSSOLogin();

      if (session) {
        setSession(session);
        router.replace("/dashboard");
        return;
      }

      if (url) {
        setStatus("redirecting");
        window.location.href = url;
        return;
      }

      throw new Error("No login URL or session returned");
    } catch (error) {
      setStatus("error");
      setLoginError(error instanceof Error ? error.message : String(error));
    }
  }, [router, setSession, startSSOLogin]);

  useEffect(() => {
    const reason = params?.get("reason");
    if (!reason) return;
    if (reason === "invalid_token" || reason === "session_expired") {
      setNotice({
        kind: "warning",
        title: "Session expired",
        description: "Your previous session is no longer valid. Sign in again to continue.",
      });
      router.replace("/auth/login");
      return;
    }
    if (reason === "sso_failed") {
      setNotice({
        kind: "warning",
        title: "SSO sign-in failed",
        description: "The identity provider returned an error. Review the message on this page, fix the provider configuration if needed, then retry manually.",
      });
      return;
    }
    if (reason) {
      setNotice({
        kind: "info",
        title: "Sign in required",
        description: "Please sign in to access the dashboard.",
      });
      router.replace("/auth/login");
    }
  }, [params, router]);

  useEffect(() => {
    setHasMounted(true);
    if (typeof window !== "undefined") {
      setHostname(window.location.hostname);
    }

    let cancelled = false;
    const load = async () => {
      try {
        const branding = await fetchPlatformBranding();
        if (cancelled) return;
        const title = branding.display_name?.trim();
        if (title) {
          setDisplayName(title);
          document.title = title;
        }
      } catch {
        // Ignore branding errors on login; use default copy.
      }
    };
    void load();
    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    if (!hasMounted || reason === "sso_failed" || status !== "idle" || loginError || autoLoginAttemptedRef.current) {
      return;
    }
    autoLoginAttemptedRef.current = true;
    void handleLogin();
  }, [handleLogin, hasMounted, loginError, reason, status]);

  return (
    <div
      role="main"
      style={{
        minHeight: "100dvh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: 24,
        background:
          "radial-gradient(circle at top left, rgba(99, 102, 241, 0.14), transparent 30%), linear-gradient(180deg, #f8fafc 0%, #eef2ff 100%)",
      }}
    >
      <Card style={{ width: "min(560px, 100%)", boxShadow: "0 20px 50px rgba(15, 23, 42, 0.10)" }} styles={{ body: { padding: 32 } }}>
        <div style={{ marginBottom: 24 }}>
          <Paragraph type="secondary" style={{ marginBottom: 8, textTransform: "uppercase", letterSpacing: "0.08em" }}>
            {PROVIDER_LABEL} sign-in
          </Paragraph>
          <Title level={3} style={{ marginTop: 0, marginBottom: 8 }}>
            {displayName}
          </Title>
          <Paragraph style={{ marginBottom: 0 }}>
            Continue with your organization account. SSO starts automatically unless you need to retry.
          </Paragraph>
        </div>

        {notice ? (
          <Alert
            showIcon
            type={notice.kind === "warning" ? "warning" : "info"}
            message={notice.title}
            description={notice.description}
            style={{ marginBottom: 16 }}
          />
        ) : null}

        {loginError ? (
          <Alert
            showIcon
            type="error"
            message="Sign-in could not start"
            description={loginError}
            style={{ marginBottom: 16 }}
          />
        ) : null}

        <form
          onSubmit={(event) => {
            event.preventDefault();
            void handleLogin();
          }}
        >
          <Button
            type="primary"
            htmlType="submit"
            loading={status === "starting" || status === "redirecting"}
            block
            aria-label={LOGIN_CTA}
          >
            {status === "redirecting" ? "Redirecting..." : reason === "sso_failed" ? `Retry ${PROVIDER_LABEL} SSO` : LOGIN_CTA}
          </Button>
          <Paragraph role="status" aria-live="polite" style={{ marginTop: 12, marginBottom: 0 }}>
            <Text type={status === "error" ? "danger" : "secondary"}>{statusCopy}</Text>
          </Paragraph>
        </form>
      </Card>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense
      fallback={
        <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Card style={{ width: 320 }}>
            <Paragraph style={{ marginBottom: 0 }}>Loading sign-in...</Paragraph>
          </Card>
        </div>
      }
    >
      <LoginContent />
    </Suspense>
  );
}
