import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";
import { Check, Monitor } from "lucide-react";
import { useState } from "react";
import { AuthShell } from "../features/auth/AuthShell";
import { ensureDeviceSession, syncWebDeviceName } from "../features/auth/auth";
import { persistDesktopDeviceName } from "../net/desktop";
import { useAppStore } from "../store";
import { t } from "../i18n";
import { isAsciiDeviceName } from "../utils/format";
import { toast } from "../ui/feedback";
import { Button, TextField } from "../ui/primitives";

export const Route = createFileRoute("/setup")({
    component: SetupPage,
    beforeLoad: () =>
    {
        const { user } = useAppStore.getState();
        if (!user) { throw redirect({ to: "/login", search: { dev_user: undefined } }); }
    },
});

// 首次为本机命名。后端 middleware 在首次认证请求时 UPSERT 进 devices 表，
// 因此这里只负责把名字写进 localStorage，让路由守卫不再跳转到此页。
function SetupPage()
{
    const navigate = useNavigate();
    const setSelfDeviceName = useAppStore((s) => s.setSelfDeviceName);
    const [ name, setName ] = useState(suggestDefault());
    const [ saving, setSaving ] = useState(false);

    const handleSave = async () =>
    {
        if (saving) { return; } // 防重复提交：代铸期间再次点击会多铸一条设备会话
        const trimmed = name.trim();
        if (!trimmed) { return; }
        if (!isAsciiDeviceName(trimmed))
        {
            toast.warn(t("settings.deviceName.asciiOnly"));
            return;
        }
        setSaving(true);
        try
        {
            setSelfDeviceName(trimmed);
            persistDesktopDeviceName(trimmed); // 桌面：持久化到 Go 配置，跨重启存活
            syncWebDeviceName(trimmed);        // 浏览器：持久化到服务端 session，抗 PWA 存储清除
            // 浏览器：名字既定，立即代铸一条托管设备会话（桌面 / 已持令牌者为 no-op），
            // 使本机以此名进入统一设备列表后再进入应用。
            await ensureDeviceSession();
            navigate({ to: "/" });
        }
        finally
        {
            setSaving(false);
        }
    };

    return (
        <AuthShell
            title={t("setup.title")}
            subtitle={t("setup.help")}
            hideBrand
            footer={
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                    <Monitor size={12} />
                    本机将以此名字展示给其他设备
                </span>
            }
        >
            <TextField
                label={t("setup.field")}
                value={name}
                onChange={(e) => setName(e.currentTarget.value)}
                onKeyDown={(e) =>
                {
                    if (e.key === "Enter" && name.trim())
                    {
                        e.preventDefault();
                        handleSave();
                    }
                }}
                autoFocus
            />
            <Button
                variant="primary"
                size="lg"
                block
                leftIcon={<Check size={16} />}
                onClick={handleSave}
                disabled={!name.trim() || saving}
            >
                {t("setup.save")}
            </Button>
        </AuthShell>
    );
}

function suggestDefault(): string
{
    const ua = navigator.userAgent;
    let browser = "Browser";
    if (ua.includes("Firefox/")) { browser = "Firefox"; }
    else if (ua.includes("Edg/")) { browser = "Edge"; }
    else if (ua.includes("Chrome/")) { browser = "Chrome"; }
    else if (ua.includes("Safari/")) { browser = "Safari"; }

    let os = "Desktop";
    if (ua.includes("Mac")) { os = "macOS"; }
    else if (ua.includes("Windows")) { os = "Windows"; }
    else if (ua.includes("Linux")) { os = "Linux"; }

    return `${browser}-${os}-${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, "0")}`;
}
