import { AlertTriangle, ExternalLink, LogIn, ShieldHalf } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useAuth } from "react-oidc-context";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Button } from "../../components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "../../components/ui/card";
import { canStartBrowserPkceLogin } from "../../lib/authConfig";
import { debugLog } from "../../lib/debugLog";

const insecurePkceMessage =
  "이 주소에서는 브라우저 보안 정책 때문에 SSO 로그인을 시작할 수 없습니다. HTTPS 또는 localhost로 접속하거나, 내부망/host.docker.internal 개발 접속은 Chrome의 insecure-origin secure context 옵션에 실제 auth UI origin(예: http://host.docker.internal:5000)을 정확히 등록해 주세요.";

function isPkceSetupFailure(error: unknown) {
  const message = error instanceof Error ? error.message : String(error);
  return /Crypto\.subtle|WebCrypto|PKCE|secure context|subtle/i.test(message);
}

function LoginPage() {
  const auth = useAuth();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const autoStartedRef = useRef(false);
  const [loginError, setLoginError] = useState<string | null>(null);
  const returnTo = searchParams.get("returnTo") || "/";
  const shouldAutoLogin = searchParams.get("auto") === "1";
  const authErrorMessage = useMemo(() => {
    const message = auth.error?.message;
    if (!message) {
      return null;
    }
    if (message.includes("Crypto.subtle")) {
      return insecurePkceMessage;
    }
    return message;
  }, [auth.error?.message]);
  const visibleLoginError = loginError || authErrorMessage;

  useEffect(() => {
    debugLog("[LoginPage] Auth state check:", {
      isAuthenticated: auth.isAuthenticated,
      isLoading: auth.isLoading,
      returnTo,
    });
    if (auth.isAuthenticated) {
      console.info(
        "[LoginPage] User is authenticated, redirecting to",
        returnTo,
      );
      navigate(returnTo, { replace: true });
    }
  }, [auth.isAuthenticated, navigate, returnTo, auth.isLoading]);

  useEffect(() => {
    if (!shouldAutoLogin) {
      return;
    }
    if (autoStartedRef.current || auth.isLoading || auth.activeNavigator) {
      return;
    }
    if (!canStartBrowserPkceLogin()) {
      setLoginError(insecurePkceMessage);
      return;
    }

    autoStartedRef.current = true;
    void auth
      .signinRedirect({
        state: {
          returnTo,
        },
      })
      .catch((error) => {
        if (isPkceSetupFailure(error)) {
          setLoginError(insecurePkceMessage);
          return;
        }
        console.error("Auto login redirect failed", error);
      });
  }, [auth, auth.activeNavigator, auth.isLoading, returnTo, shouldAutoLogin]);

  const handleSSOLogin = async () => {
    try {
      setLoginError(null);
      if (!canStartBrowserPkceLogin()) {
        setLoginError(insecurePkceMessage);
        return;
      }
      await auth.signinRedirect({
        state: {
          returnTo,
        },
      });
    } catch (error) {
      if (isPkceSetupFailure(error)) {
        setLoginError(insecurePkceMessage);
        return;
      }
      console.error("Redirect login failed", error);
    }
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-background px-4 py-12 sm:px-6 lg:px-8 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-primary/10 via-background to-background">
      <div className="w-full max-w-md space-y-8">
        <div className="flex flex-col items-center justify-center space-y-4 text-center">
          <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-primary/15 text-primary shadow-[0_20px_50px_rgba(54,211,153,0.3)]">
            <ShieldHalf size={32} />
          </div>
          <div className="space-y-2">
            <h1 className="text-3xl font-bold tracking-tight">Baron SSO</h1>
            <p className="text-sm text-muted-foreground uppercase tracking-[0.2em]">
              Admin Control Plane
            </p>
          </div>
        </div>

        {auth.error && (
          <div className="rounded-lg bg-destructive/15 p-4 text-sm text-destructive border border-destructive/20 animate-in fade-in slide-in-from-top-1">
            <div className="font-bold flex items-center gap-2 mb-1">
              <ShieldHalf size={16} />
              인증 오류가 발생했습니다
            </div>
            <p className="opacity-90">{auth.error.message}</p>
            <Button
              variant="ghost"
              className="p-0 h-auto text-destructive underline mt-2 hover:bg-transparent"
              onClick={() => {
                void handleSSOLogin();
              }}
            >
              다시 시도하기
            </Button>
          </div>
        )}

        <Card className="border-primary/20 bg-card/50 backdrop-blur-xl shadow-2xl">
          <CardHeader className="space-y-1">
            <CardTitle className="text-2xl flex items-center gap-2">
              <LogIn size={20} className="text-primary" />
              관리자 로그인
            </CardTitle>
            <CardDescription>
              Baron 통합 인증(SSO)을 통해 관리자 페이지에 접속합니다.
            </CardDescription>
          </CardHeader>
          <CardContent className="pt-4 pb-8 space-y-3">
            <Button
              onClick={handleSSOLogin}
              className="w-full h-14 text-lg font-semibold flex gap-3 shadow-lg"
              disabled={auth.isLoading}
            >
              {auth.isLoading ? (
                <>
                  <div className="h-5 w-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                  로그인 진행 중...
                </>
              ) : (
                <>
                  <ShieldHalf size={22} />
                  SSO 계정으로 로그인
                  <ExternalLink size={16} className="opacity-50" />
                </>
              )}
            </Button>

            {visibleLoginError ? (
              <div
                role="alert"
                className="flex gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm leading-5 text-destructive"
              >
                <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
                <span>{visibleLoginError}</span>
              </div>
            ) : null}

            <p className="mt-6 text-xs text-center text-muted-foreground leading-relaxed">
              관리자 전역 세션은 보안을 위해 15분간 유지됩니다.
              <br />
              민감한 작업 시 재인증을 요구할 수 있습니다.
            </p>
          </CardContent>
        </Card>

        <div className="flex justify-center gap-4">
          <div className="h-1 w-1 rounded-full bg-primary/30" />
          <div className="h-1 w-1 rounded-full bg-primary/30" />
          <div className="h-1 w-1 rounded-full bg-primary/30" />
        </div>

        <p className="px-8 text-center text-sm text-muted-foreground">
          인증 정보가 없거나 로그인이 되지 않는 경우
          <br />
          시스템 관리자에게 문의하세요.
        </p>
      </div>
    </div>
  );
}

export default LoginPage;
