import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { AlertTriangle, LogIn, QrCode } from "lucide-react";
import { useEffect, useState } from "react";
import { loginDev, loginRedirect } from "../features/auth/auth";
import { isDesktop, startDesktopLogin } from "../net/desktop";
import { AuthShell } from "../features/auth/AuthShell";
import { useAppStore } from "../store";
import { t } from "../i18n";
import { Button, Callout, TextField } from "../ui/primitives";

export const Route = createFileRoute("/login")({
    component: LoginPage,
    validateSearch: (search: Record<string, unknown>) =>
    ({
        dev_user: typeof search.dev_user === "string" ? search.dev_user : undefined,
    }),
});

function LoginPage()
{
    const navigate = useNavigate();
    const search = Route.useSearch();
    const localAuthMode = useAppStore((s) => s.authMode);
    const user = useAppStore((s) => s.user);

    const [ devUser, setDevUser ] = useState(search.dev_user ?? "");
    const [ error, setError ] = useState<string | null>(null);

    // 已登录态落在 /login 时反应式跳首页。全局 SSO 登录回跳后 rd 指回本页（登录前用户
    // 被 __root 守卫从原路由送到了 /login），bootstrapAuth 据 broker cookie 注入身份后
    // 若不主动离开，就停在登录页形成“登录成功却又见登录页”的回环。__root 的守卫只把
    // 未登录态送进 /login，登录态的反向跳转由此补齐（含 dev 同步登录后的兜底）。
    useEffect(() =>
    {
        if (user) { navigate({ to: "/" }); }
    }, [ user, navigate ]);

    // 后端不再暴露 /api/auth/config（OIDC 已委托给 broker）；登录模式以前端编译期
    // 注入的 authMode 为准（dev / prod）。
    const effectiveMode = localAuthMode;

    const handleDevLogin = () =>
    {
        try
        {
            const params = new URLSearchParams();
            if (devUser) { params.set("dev_user", devUser); }
            loginDev(params);
            navigate({ to: "/" });
        }
        catch (e)
        {
            setError(e instanceof Error ? e.message : String(e));
        }
    };

    const handleProdLogin = async () =>
    {
        try
        {
            // 桌面端走 Go loopback PKCE 桥（浏览器重定向式登录不适用于 WebView）；
            // 成功后由 startDesktopLogin 写好 token + 设备名，这里只负责跳首页。
            if (isDesktop())
            {
                await startDesktopLogin();
                navigate({ to: "/" });
            }
            else
            {
                // 跳到 broker 全局 SSO 登录（cdrop 后端 302 代跳）；登录后回跳本页，
                // 边缘 human 分支据 broker cookie 注入身份。
                loginRedirect();
            }
        }
        catch (e) { setError(e instanceof Error ? e.message : String(e)); }
    };

    return (
        <AuthShell
            title={t("login.title")}
            subtitle="在你的多台设备之间快速传输文件、消息与剪贴板。"
            footer={`© ${new Date().getFullYear()} Commilitia Drop`}
        >
            {error && (
                <Callout tone="error" icon={<AlertTriangle size={16} />}>
                    {error}
                </Callout>
            )}
            {effectiveMode === "dev"
                ? (
                    <>
                        <Callout tone="warn">
                            {t("login.dev.help")}
                        </Callout>
                        <TextField
                            label={t("login.dev.field")}
                            placeholder="alice"
                            value={devUser}
                            onChange={(e) => setDevUser(e.currentTarget.value)}
                            onKeyDown={(e) =>
                            {
                                if (e.key === "Enter") { e.preventDefault(); handleDevLogin(); }
                            }}
                        />
                        <Button
                            variant="primary"
                            size="lg"
                            block
                            leftIcon={<LogIn size={16} />}
                            onClick={handleDevLogin}
                        >
                            {t("login.dev.continue")}
                        </Button>
                    </>
                )
                : (
                    <>
                        <p data-jz-level="paragraph" style={{
                            margin: 0,
                            fontSize: "var(--fs-13)",
                            lineHeight: "var(--lh-body)",
                            color: "var(--text-muted)",
                        }}>
                            {t("login.prod.help")}
                        </p>
                        <Button
                            variant="primary"
                            size="lg"
                            block
                            leftIcon={<LogIn size={16} />}
                            onClick={handleProdLogin}
                        >
                            {t("login.prod.button")}
                        </Button>
                        {/* 扫码登录入口：与 OAuth 登录平级的另一种登录方式——从已登录的
                            另一台设备批准本机接入，无需在此重登。secondary 变体、等宽、
                            同 size，与主登录按钮同级视觉重量。 */}
                        <Button
                            variant="secondary"
                            size="lg"
                            block
                            leftIcon={<QrCode size={16} />}
                            onClick={() => navigate({ to: "/link/new" })}
                        >
                            {t("qr.entry.fromLogin")}
                        </Button>
                    </>
                )}
        </AuthShell>
    );
}
