import dash
from dash import Dash, dcc, html

try:
    from mpstyle.core.mpshipsapp import MPShipsApp

    MPSTYLE_INSTALLED = True
    BaseApp = MPShipsApp
except ImportError:
    from .core.mpshipsapp import MPShipsApp

    MPSTYLE_INSTALLED = False
    BaseApp = MPShipsApp
    print("No mpstyle available. Local development setting is used")

BULMA_CSS = "https://cdn.jsdelivr.net/npm/bulma@1.0.0/css/bulma.min.css"


def create_app(url="/", pages_folder="pages") -> Dash:
    """
    Create a "naked" app with minimum bulma styling

    Returns:
        Dash app
    """
    # infra_css_url = "/_mpships_infra/mpships.css"

    app = Dash(
        __name__,
        assets_folder="assets/",
        external_scripts=[
            "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML",
            "https://materialsproject.statuspage.io/embed/script.js",
            BULMA_CSS,
        ],
        use_pages=True,
        suppress_callback_exceptions=True,
        requests_pathname_prefix=url,
        routes_pathname_prefix=url,
        pages_folder=pages_folder,
    )

    # styling
    GLOBAL_BANNER = None
    NAVBAR_LAYOUT = None
    footer = None
    user_settings_modal = None

    # MP styling
    if MPSTYLE_INSTALLED:
        # GLOBAL_BANNER
        from mpstyle.constants import GLOBAL_BANNER_MARKDOWN, GLOBAL_BANNER_VARIETY

        if GLOBAL_BANNER_MARKDOWN:
            GLOBAL_BANNER = html.Div(
                [
                    dcc.Markdown(GLOBAL_BANNER_MARKDOWN),
                ],
                className=f"global-banner notification is-{GLOBAL_BANNER_VARIETY} m-0 pb-3 pt-3 has-text-centered",
            )

        # NAVBAR_LAYOUT
        # footer
        from mpstyle.layouts.footer import footer
        from mpstyle.layouts.navbar import NAVBAR_LAYOUT

        # get_user_settings_modal
        from mpstyle.layouts.user_settings_modal import get_user_settings_modal

        user_settings_modal = get_user_settings_modal()

    main_layout = html.Div(
        [
            html.Div(
                className="mp-container",
                children=[
                    dcc.Location(id="mp-url", refresh=False),
                    dcc.Store(
                        id="mp-title-meta",
                        data={
                            "title": "Materials Project",
                            "meta": "Materials Project",
                        },
                    ),
                    GLOBAL_BANNER,
                    NAVBAR_LAYOUT,
                    dash.page_container,
                    html.Div(id="request-headers", className="is-hidden"),
                ],
            ),
            footer,
            user_settings_modal,
            html.Div(id="dummy-content"),
        ]
    )

    app.layout = main_layout

    return app
