'use client';

import React, {
    createContext,
    useCallback,
    useContext,
    useEffect,
    useMemo,
    useState,
    type ReactNode,
} from 'react';

export type PageShellOptionsConfig = {
    /**
     * Main sem card cinza centralizado (max-width 1600px) — largura útil total.
     * Opt-in por página via `<PageShellOptions contentBoardBleed />`.
     */
    contentBoardBleed?: boolean;
    /** Oculta o rodapé institucional do shell (ex.: detalhe tarefa mobile-first). */
    hideAppFooter?: boolean;
    /**
     * Oculta a navegação inferior global no mobile quando a página traz barra fixa própria
     * (ex.: detalhe de tarefa com `TarefaDetalheMobileBar`).
     * Preferir {@link useMobilePageActionBarRegistration} em barras fixas reutilizáveis.
     */
    hideMobileBottomNav?: boolean;
};

type PageShellOptionsContextValue = {
    options: PageShellOptionsConfig | null;
    setOptions: (options: PageShellOptionsConfig | null) => void;
    mobilePageActionBarCount: number;
    registerMobilePageActionBar: () => () => void;
    /** Só oculta `MobileBottomNav` (ex.: `PageHeader.actionsMobileBar`), sem contar como barra dedicada. */
    mobileBottomNavHideCount: number;
    registerHideMobileBottomNav: () => () => void;
};

const PageShellOptionsContext = createContext<PageShellOptionsContextValue | null>(null);

export function PageShellOptionsProvider({ children }: { children: ReactNode }) {
    const [options, setOptions] = useState<PageShellOptionsConfig | null>(null);
    const [mobilePageActionBarCount, setMobilePageActionBarCount] = useState(0);
    const [mobileBottomNavHideCount, setMobileBottomNavHideCount] = useState(0);

    const registerMobilePageActionBar = useCallback(() => {
        setMobilePageActionBarCount((count) => count + 1);
        return () => {
            setMobilePageActionBarCount((count) => Math.max(0, count - 1));
        };
    }, []);

    const registerHideMobileBottomNav = useCallback(() => {
        setMobileBottomNavHideCount((count) => count + 1);
        return () => {
            setMobileBottomNavHideCount((count) => Math.max(0, count - 1));
        };
    }, []);

    const value = useMemo(
        () => ({
            options,
            setOptions,
            mobilePageActionBarCount,
            registerMobilePageActionBar,
            mobileBottomNavHideCount,
            registerHideMobileBottomNav,
        }),
        [
            options,
            mobilePageActionBarCount,
            registerMobilePageActionBar,
            mobileBottomNavHideCount,
            registerHideMobileBottomNav,
        ],
    );

    return (
        <PageShellOptionsContext.Provider value={value}>{children}</PageShellOptionsContext.Provider>
    );
}

export function usePageShellOptionsState(): PageShellOptionsConfig | null {
    return useContext(PageShellOptionsContext)?.options ?? null;
}

export function usePageShellOptionsSetter(): (options: PageShellOptionsConfig | null) => void {
    const ctx = useContext(PageShellOptionsContext);
    if (!ctx) {
        throw new Error('PageShellOptions deve ser usado dentro de AntLayout (PageShellOptionsProvider).');
    }
    return ctx.setOptions;
}

/** Indica se alguma barra fixa de ações de página dedicada está ativa (mobile). */
export function useMobilePageActionBarActive(): boolean {
    const ctx = useContext(PageShellOptionsContext);
    return (ctx?.mobilePageActionBarCount ?? 0) > 0;
}

/** Indica se o `MobileBottomNav` deve ficar oculto (barra dedicada ou claim do PageHeader). */
export function useMobileBottomNavSuppressed(): boolean {
    const ctx = useContext(PageShellOptionsContext);
    return (
        (ctx?.mobilePageActionBarCount ?? 0) > 0 || (ctx?.mobileBottomNavHideCount ?? 0) > 0
    );
}

/**
 * Regista uma barra fixa mobile no shell — oculta `MobileBottomNav` enquanto montada.
 * Usar em `MobilePageActionBar` e barras custom equivalentes.
 */
export function useMobilePageActionBarRegistration(active = true): void {
    const ctx = useContext(PageShellOptionsContext);
    /** Estável — não depender de `ctx` (identity muda com o count). */
    const registerMobilePageActionBar = ctx?.registerMobilePageActionBar;

    useEffect(() => {
        if (!active || !registerMobilePageActionBar) {
            return;
        }
        return registerMobilePageActionBar();
    }, [active, registerMobilePageActionBar]);
}

/**
 * Oculta só o `MobileBottomNav` sem marcar barra dedicada.
 * Usar na `PageHeader.actionsMobileBar` para não empilhar com o nav global.
 */
export function useHideMobileBottomNav(active = true): void {
    const ctx = useContext(PageShellOptionsContext);
    /** Estável — não depender de `ctx` (identity muda com o count). */
    const registerHideMobileBottomNav = ctx?.registerHideMobileBottomNav;

    useEffect(() => {
        if (!active || !registerHideMobileBottomNav) {
            return;
        }
        return registerHideMobileBottomNav();
    }, [active, registerHideMobileBottomNav]);
}
