import { Link, usePage } from '@inertiajs/react';
import { Shield } from 'lucide-react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import type { User } from '@/types';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { edit as securityEdit } from '@/routes/security';

const STORAGE_KEY = 'jabesfx_dismiss_two_factor_suggestion';

function shouldPrompt(user: User | undefined, unlocked: boolean): boolean {
    if (!user?.email_verified_at) return false;
    if (!unlocked) return false;
    if (user.two_factor_confirmed_at) return false;

    return true;
}

export function TwoFactorSuggestionBanner() {
    type PageProps = {
        auth?: { user?: User };
        kyc?: { investor_portal_unlocked?: boolean };
    };

    const page = usePage<PageProps>();

    const user = page.props.auth?.user;
    const unlocked =
        page.props.kyc?.investor_portal_unlocked === true ||
        user?.is_admin === true;
    const [dismissed, setDismissed] = useState(false);

    useEffect(() => {
        setDismissed(window.localStorage.getItem(STORAGE_KEY) === '1');
    }, []);

    const visible = useMemo(
        () => shouldPrompt(user, unlocked) && !dismissed,
        [user, unlocked, dismissed],
    );

    const dismiss = useCallback(() => {
        window.localStorage.setItem(STORAGE_KEY, '1');
        setDismissed(true);
    }, []);

    if (!visible) {
        return null;
    }

    return (
        <Alert className="border-primary/35 bg-primary/10">
            <Shield className="size-4" aria-hidden />
            <AlertTitle>Más seguridad para su cuenta</AlertTitle>
            <AlertDescription className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                <span className="text-sm leading-relaxed">
                    Su identidad está verificada. Active{' '}
                    <span className="font-medium text-foreground">
                        verificación en dos pasos (2FA)
                    </span>{' '}
                    para proteger su sesión ante accesos no autorizados.
                </span>
                <div className="flex shrink-0 flex-wrap gap-2">
                    <Button size="sm" asChild variant="outline">
                        <Link href={securityEdit()} prefetch>
                            Configurar en Seguridad
                        </Link>
                    </Button>
                    <Button
                        variant="ghost"
                        size="sm"
                        type="button"
                        className="text-muted-foreground"
                        onClick={dismiss}
                    >
                        Ocultar
                    </Button>
                </div>
            </AlertDescription>
        </Alert>
    );
}
