"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { API_BASE, ApiError, NotConnected, api } from "@/lib/api";
import { NotConnectedPanel } from "@/components/NotConnected";
import { Button } from "@/components/Button";
import { Field } from "@/components/Field";

const SITE_URL = (process.env.NEXT_PUBLIC_SITE_URL ?? "").replace(/\/$/, "");

export default function LoginPage() {
    const router = useRouter();
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [staff, setStaff] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [offline, setOffline] = useState(false);
    const [busy, setBusy] = useState(false);

    async function submit(e: React.FormEvent) {
        e.preventDefault();
        setBusy(true);
        setError(null);
        try {
            const s = staff
                ? await api.staffLogin(email, password)
                : await api.login(email, password);
            router.replace(s.kind === "staff" ? "/staff" : "/");
        } catch (err) {
            if (err instanceof NotConnected) setOffline(true);
            else if (err instanceof ApiError) setError(err.message);
            else setError("Sign in failed. Try again.");
        } finally {
            setBusy(false);
        }
    }

    if (offline)
        return (
            <Main>
                <NotConnectedPanel url={API_BASE} />
            </Main>
        );

    return (
        <Main>
            {/* The masthead's lockup, unlinked: there is nowhere to go yet. */}
            <div className="mb-7 flex flex-col items-center gap-2 text-center">
                <span className="flex items-baseline gap-2 text-[1.5rem] font-extrabold tracking-[-0.02em]">
                    Vantage
                    <span className="font-mono text-[0.78rem] font-normal uppercase tracking-[0.14em] text-ink-3">
                        HQ
                    </span>
                </span>
                <h1 className="text-[1.16rem]">Sign in</h1>
                <p className="font-mono text-[0.72rem] uppercase tracking-[0.1em] text-ink-3">
                    Licences · instances · billing
                </p>
            </div>

            <div className="rounded border border-rule bg-panel p-6 shadow-[var(--shadow)]">
                <form onSubmit={submit} className="grid gap-4">
                    <Field
                        label="Email"
                        type="email"
                        autoComplete="username"
                        required
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                    />
                    <Field
                        label="Password"
                        type="password"
                        autoComplete="current-password"
                        required
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        error={error ?? undefined}
                    />
                    <label className="flex items-center gap-2 text-[0.82rem] text-ink-2">
                        <input
                            type="checkbox"
                            checked={staff}
                            onChange={(e) => setStaff(e.target.checked)}
                            className="accent-[var(--accent)]"
                        />
                        I work at Vantage
                    </label>
                    <Button type="submit" disabled={busy} className="w-full justify-center">
                        {busy ? "Signing in…" : "Sign in"}
                    </Button>
                </form>

                {SITE_URL && (
                    <>
                        <div className="my-5 h-px bg-rule-soft" />

                        {/* Signup lives on the marketing site's /start, not here. */}
                        <p className="text-center text-[0.82rem] text-ink-3">
                            No account?{" "}
                            <a href={`${SITE_URL}/start`} className="text-accent underline">
                                Create one
                            </a>
                        </p>
                    </>
                )}
            </div>
        </Main>
    );
}

function Main({ children }: { children: React.ReactNode }) {
    return (
        <main className="mx-auto flex min-h-screen w-full max-w-[26rem] flex-col justify-center px-5 py-12">
            {children}
        </main>
    );
}
