import solara
from solara import component

from pathlib import Path

from datetime import datetime

# Get current date in YYYY-MM-DD format
end_date = datetime.today().strftime("%Y-%m-%d")

basis_options = [
    "OBSERVATION - An occurrence record describing an observation",
    "OCCURRENCE - An existence of an organism at a particular place at a particular time",
    "FOSSIL_SPECIMEN - A specimen that is a fossil",
    "HUMAN_OBSERVATION - Evidence of an occurrence without physical or machine evidence",
    "LIVING_SPECIMEN - A specimen that is alive",
    "MACHINE_OBSERVATION - Evidence of an occurrence thorough physical or machine evidence (e.g. photograph, video, etc.)",
    "MATERIAL_CITATION - A citation of a specimen in a scholarly publication",
    "PRESERVED_SPECIMEN - A specimen that has been preserved",
]

# Reactive state for filter toggle
filter_mode = solara.reactive("Simple Filters")


@solara.component
def FilterSection():
    # Toggle buttons + conditional content
    solara.ToggleButtonsSingle(
        value=filter_mode,
        values=["Simple Filters", "Advanced Filters"],
        style={"display": "flex", "justifyContent": "center", "marginBottom": "10px"},
    )

    if filter_mode.value == "Simple Filters":
        solara.Markdown(
            """
            **GBIF Data**
            - GBIF Limit

            **Biology**
            - Baseline Mortality

            **Output**
            - Raster Resolution
            """
        )
    else:
        solara.Markdown(
            """
            **GBIF Data**
            - GBIF Limit
            - Start Year
            - End Date
            - Bounding Box
            - Basis of Record

            **Biology**
            - Baseline Mortality
            - Distance Decay
            - Directional Modifier

            **Output**
            - Raster Resolution
            """
        )


@solara.component
def Page():
    solara.Style(Path("solara/assets/custom.css"))

    with solara.Column(align="center", gap="1rem"):
        # Title (centered, bold)
        solara.Markdown(
            "# **Quick guide to using _ecospat_ for basic and advanced analyses**"
        )

        # Subtitle
        solara.Markdown(
            "##_Learn about what GBIF data, biological, and output filters mean in ecospat and how to use them._",
            style={"text-align": "center"},
        )

        solara.Markdown(
            "### To explore an application of data generated by _ecospat_, checkout a [use-case](/use-case)."
        )

        image_url = "images/logo.png"
        solara.Image(image_url, width="200px")

        solara.Markdown(
            """
                        ###_ecospat_ is a tool that uses GBIF data to categorize the range edges of species through time to understand patterns of movement, population dynamics, and persistence.

                        """
        )

        with solara.Column(style={"text-align": "left"}):
            solara.Markdown(
                """
                            ## A search begins by entering a species scientific name.
                            If the species is unavailable on GBIF it will return the original search window.
                            """
            )
            solara.InputText(label="Species", value=""),
            solara.Button(
                "Search",
                style={"width": "100%", "marginTop": "10px", "marginBottom": "10px"},
            ),
            solara.Markdown(
                """
                            ### However, the range edges and estimates of species persistence depend on the data and biological parameters specified by the user.
                            """
            )

        # Body text inside container
        with solara.Column(style={"text-align": "left"}):
            solara.Markdown(
                """
                            ## Simple and advanced filters can be accessed and changed using buttons
                            """
            )

            FilterSection()

            with solara.Column(style={"max-width": "800px", "gap": "1rem"}):

                with solara.Card(title="GBIF Filters"):
                    solara.Markdown(
                        "**GBIF Limit:** Maximum number of GBIF occurrence records to use. Recommended: 2000–4000. Processing time increases with more records, and some species may have fewer available occurrences."
                    )
                    solara.InputInt("GBIF Limit", value=2000)

                    solara.Markdown(
                        "**Start Year:** Start of historical distribution. Only required for global species not found in Little's range maps of North American tree species."
                    )
                    solara.InputText(
                        "Start Year (only required for global species)", value=""
                    )

                    solara.Markdown("**End Date:** End of modern distribution.")
                    solara.InputText("End Date", value=end_date)

                    solara.Markdown(
                        "**Bounding Box**  \nGeographic limits for filtering GBIF occurrence records. Defaults are set for North America."
                    )
                    solara.InputText("Latitudinal Minimum", value=6.6)
                    solara.InputText("Latitudinal Maximum", value=83.3)
                    solara.InputText("Longitudinal Minimum", value=-178.2)
                    solara.InputText("Longitudinal Maximum", value=-49)

                    solara.Markdown(
                        "**Basis of Record**  \nSpecific nature of the GBIF record."
                    )
                    for option in basis_options:
                        solara.Checkbox(label=option, value=False)

                with solara.Card(title="Biology Filters"):
                    solara.Markdown(
                        "**Baseline Mortality:** The proportion of individuals in a population that die within one year."
                    )
                    solara.InputFloat("Baseline Mortality", value=0.1)

                    solara.Markdown(
                        "**Distance Decay:** The speed at which propagule pressure decreases with distance from an occupied cell (e.g. dispersal capability)."
                    )
                    solara.InputFloat("Distance Decay", value=0.3)

                    solara.Markdown(
                        "**Directional Modifier:** The strength of northward or southward movement on propagule pressure."
                    )
                    solara.InputFloat("Directional Modifier", value=10)

                with solara.Card(title="Output Filters"):
                    solara.Markdown(
                        "**Raster Resolution:** Size of one raster cell (0.1667° ≈ 400 km²). Higher resolution increases computational time."
                    )
                    solara.InputFloat("Raster Resolution", value=0.1666667)

        with solara.Column(
            style={
                "text-align": "left",
                "padding-bottom": "3vh",
                "margin-bottom": "50px",
            }
        ):
            solara.Markdown(
                """
            ## Generated Data is available for download using download buttons under summary statistics and maps
            """,
                style={"text-align": "center"},
            )

            with solara.Row(style={"display": "flex", "justify-content": "center"}):
                MockFileDownload()


@solara.component
def MockFileDownload():
    # Empty bytes to simulate a download
    empty_file = b""

    return solara.FileDownload(
        data=empty_file,
        filename="example.csv",
        label="Download Example CSV",
    )
