import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { AlertTriangle, LogIn, QrCode } from "lucide-react";
import { useEffect, useState } from "react";
import { fetchAuthConfig, loginDev, loginProd } 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 [ devUser, setDevUser ] = useState(search.dev_user ?? "");
    const [ error, setError ] = useState<string | null>(null);
    // 前端编译期推断的 mode（DEV/PROD）可能与后端实际部署不一致
    // （例如把 prod 构建打到 dev 后端测试），因此以服务器返回的为准。
    const [ serverMode, setServerMode ] = useState<"dev" | "prod" | null>(null);

    useEffect(() =>
    {
        let cancelled = false;
        fetchAuthConfig().then(
            (cfg) => { if (!cancelled) { setServerMode(cfg.auth_mode); } },
            () => { /* 回退到编译期 mode */ },
        );
        return () => { cancelled = true; };
    }, []);

    const effectiveMode = serverMode ?? 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
            {
                await loginProd();
            }
        }
        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>
    );
}
