import { router, usePage } from '@inertiajs/react';
import { useEffect, useRef, useState } from 'react';
import { logout } from '@/routes';
import type { Auth } from '@/types';

const EVENTS = ['mousemove', 'mousedown', 'keydown', 'scroll', 'touchstart'];
const WARN_SECONDS = 60;

/**
 * Sign the person out after the inactivity time set in System settings
 * (AMCSMS §24), with a one-minute warning they can dismiss.
 */
export default function IdleLogout() {
    const { auth } = usePage<{ auth: Auth }>().props;
    const minutes = auth.idleTimeoutMinutes ?? 0;
    const lastActive = useRef(Date.now());
    const [secondsLeft, setSecondsLeft] = useState<number | null>(null);

    useEffect(() => {
        if (minutes <= 0) {
            return;
        }

        const markActive = () => {
            lastActive.current = Date.now();
            setSecondsLeft(null);
        };

        EVENTS.forEach((name) =>
            window.addEventListener(name, markActive, { passive: true }),
        );

        const timer = window.setInterval(() => {
            const idle = (Date.now() - lastActive.current) / 1000;
            const remaining = Math.ceil(minutes * 60 - idle);

            if (remaining <= 0) {
                window.clearInterval(timer);
                router.post(logout.url());
            } else if (remaining <= WARN_SECONDS) {
                setSecondsLeft(remaining);
            }
        }, 1000);

        return () => {
            window.clearInterval(timer);
            EVENTS.forEach((name) =>
                window.removeEventListener(name, markActive),
            );
        };
    }, [minutes]);

    if (secondsLeft === null) {
        return null;
    }

    return (
        <div
            role="alertdialog"
            aria-live="assertive"
            className="fixed inset-x-4 bottom-4 z-50 mx-auto flex max-w-md items-center gap-3 rounded-landing-lg border border-amber-300 bg-white p-4 text-sm shadow-landing-lg"
        >
            <span className="flex-1 text-ink-700">
                You will be signed out in {secondsLeft} seconds because of
                inactivity.
            </span>
            <button
                type="button"
                onClick={() => {
                    lastActive.current = Date.now();
                    setSecondsLeft(null);
                }}
                className="rounded-full bg-brand px-3 py-1.5 font-semibold text-white hover:bg-brand-hover"
            >
                Stay signed in
            </button>
        </div>
    );
}
