"use client";

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

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>
            <h1 className="text-3xl">Sign in</h1>
            <form onSubmit={submit} className="mt-6 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)}
                    />
                    I work at Vantage
                </label>
                <div className="flex flex-wrap items-center gap-3">
                    <Button type="submit" disabled={busy}>
                        {busy ? "Signing in…" : "Sign in"}
                    </Button>
                    <Link href="/signup" className="text-[0.82rem] text-accent underline">
                        Create an account for a self-hosted licence
                    </Link>
                </div>
            </form>
        </Main>
    );
}

function Main({ children }: { children: React.ReactNode }) {
    return <main className="mx-auto max-w-rail px-5 py-12">{children}</main>;
}
