"use client";

import { useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { ApiError, api } from "@/lib/api";
import { Button } from "@/components/Button";
import { Field } from "@/components/Field";
import { PageHeader } from "@/components/PageHeader";

export default function SettingsPage() {
    const [current, setCurrent] = useState("");
    const [next, setNext] = useState("");
    const [error, setError] = useState<string | null>(null);
    const [done, setDone] = useState<string | null>(null);

    const change = useMutation({
        mutationFn: () => api.changePassword(current, next),
        onSuccess: (res) => {
            setCurrent("");
            setNext("");
            setDone(
                res.propagation_pending
                    ? "Password changed. One of your instances could not be updated just now; it will catch up within fifteen minutes."
                    : "Password changed everywhere.",
            );
        },
        onError: (e) =>
            setError(e instanceof ApiError ? e.message : "Something went wrong. Try again."),
    });

    return (
        <div className="grid gap-6">
            <PageHeader
                back={{ href: "/", label: "Overview" }}
                title="Settings"
                subtitle="Your password signs you in here and into every Vantage instance you belong to. Changing it changes all of them."
            />

            <form
                className="grid max-w-md gap-4 rounded border border-rule bg-panel p-5"
                onSubmit={(e) => {
                    e.preventDefault();
                    setError(null);
                    setDone(null);
                    change.mutate();
                }}
            >
                <Field
                    label="Current password"
                    type="password"
                    autoComplete="current-password"
                    value={current}
                    onChange={(e) => setCurrent(e.target.value)}
                    required
                />
                <Field
                    label="New password"
                    type="password"
                    autoComplete="new-password"
                    value={next}
                    onChange={(e) => setNext(e.target.value)}
                    required
                    minLength={12}
                    hint="At least 12 characters."
                    error={error ?? undefined}
                />
                {done && <p className="text-[0.9rem] text-valid">{done}</p>}
                <Button type="submit" disabled={change.isPending || next.length < 12}>
                    {change.isPending ? "Changing…" : "Change password"}
                </Button>
            </form>
        </div>
    );
}
