# Title: Where are America's "super zips"?
# Bucket: showcase
# Description: An ipyleaflet heatmap of 10,000 US zip codes linked to four
#   plotly density plots by the map's viewport -- pan or zoom and the plots
#   redraw for just the zips in view. Zoom in far enough and the heatmap
#   swaps to colored markers; click one and its values are marked on every
#   density plot. A second tab explores the in-view zips as a data grid.
# Run: uv run --with faicons --with scipy shiny run app.py
# Data: zip-level demographics compiled for Charles Murray's "Coming Apart:
#   The State of White America, 1960-2010" (Crown Forum, 2012). A fixed
#   10,000-zip sample of the full 31,713-zip CSV, committed as
#   data/zips.parquet (rebuild with prep_data.py).

from pathlib import Path
from typing import Any

import ipyleaflet as leaf
import pandas as pd
from faicons import icon_svg
from shiny import App, reactive, render, req, ui
from shinywidgets import output_widget, render_ipyleaflet, render_plotly

from figures import HEATMAP_GRADIENT, col_numeric, create_map, density_plot
from ratelimit import debounce

app_dir = Path(__file__).parent
allzips = pd.read_parquet(app_dir / "data" / "zips.parquet")

VARIABLES = {
    "Score": "overall superzip score",
    "College": "% college educated",
    "Income": "median income",
    "Population": "population",
}
# Switch from the heatmap to individual markers once this few zips are in view
MARKER_ZIP_LIMIT = 200
# Marker color for the zip picked from the data grid (in-view markers use viridis)
GRID_MARKER_COLOR = "#fd7e14"

app_ui = ui.page_navbar(
    ui.nav_spacer(),
    ui.nav_panel(
        "Interactive map",
        ui.layout_sidebar(
            ui.sidebar(
                output_widget("density_score"),
                output_widget("density_college"),
                output_widget("density_income"),
                output_widget("density_pop"),
                position="right",
                width=300,
                title=ui.tooltip(
                    ui.span(
                        "Overall density vs in bounds",
                        icon_svg("circle-info").add_class("ms-2"),
                    ),
                    "The density plots show how various metrics behave overall (black) in comparison to within view (green).",
                ),
            ),
            ui.card(
                ui.card_header(
                    "Heatmap showing ",
                    ui.input_select("variable", None, VARIABLES, width="auto"),
                    class_="d-flex align-items-center gap-3",
                ),
                output_widget("map"),
                ui.output_ui("selected_zip"),
                ui.card_footer(
                    ui.markdown(
                        "Data compiled for _Coming Apart: The State of White America, 1960-2010_ by Charles Murray (Crown Forum, 2012)."
                    )
                ),
                full_screen=True,
            ),
        ),
    ),
    ui.nav_panel(
        "Data explorer",
        ui.layout_columns(
            ui.output_ui("data_intro"),
            ui.output_data_frame("zips_data"),
            col_widths=[3, 9],
        ),
        ui.layout_columns(
            output_widget("table_map"),
            col_widths=[-2, 8, -2],
        ),
    ),
    fillable="Interactive map",
    id="navbar",
    header=ui.include_css(app_dir / "styles.css"),
    title=ui.popover(
        [
            "Superzip explorer",
            icon_svg("circle-info").add_class("ms-2"),
        ],
        ui.markdown(
            "'Super Zips' is a term [coined by Charles Murray](https://www.amazon.com/Coming-Apart-State-America-1960-2010/dp/030745343X) to describe the most prosperous, highly educated demographic clusters"
        ),
        placement="right",
    ),
    window_title="Superzip explorer",
)


def server(input: Any, output: Any, session: Any):
    # ---------------------------------------------------------------------
    # Map viewport -> the zips in view
    # ---------------------------------------------------------------------

    @render_ipyleaflet
    def map():
        return create_map()

    # ipyleaflet reports bogus bounds while its tab is hidden, so only track
    # bounds while the map tab is showing (map.bounds() cancels until the
    # browser's first report).
    current_bounds = reactive.value()

    @reactive.effect
    def _():
        bb = map.bounds()
        if input.navbar() != "Interactive map":
            return
        with reactive.isolate():
            current_bounds.set(bb)

    # Debounced so a pan/zoom gesture settles before the plots and markers
    # redraw -- without it, every intermediate viewport triggers a redraw.
    @debounce(0.3)
    @reactive.calc
    def zips_in_bounds() -> pd.DataFrame:
        bb = req(current_bounds())
        (lat0, lon0), (lat1, lon1) = bb
        return allzips[
            allzips.Lat.between(lat0, lat1) & allzips.Long.between(lon0, lon1)
        ]

    @reactive.calc
    def show_markers() -> bool:
        return len(zips_in_bounds()) < MARKER_ZIP_LIMIT

    # ---------------------------------------------------------------------
    # Heatmap <-> marker swap
    # ---------------------------------------------------------------------

    @reactive.calc
    def heatmap_layer():
        locs = allzips[["Lat", "Long", input.variable()]].to_numpy()
        return leaf.Heatmap(
            locations=locs.tolist(),
            name="heatmap",
            gradient=HEATMAP_GRADIENT,
        )

    @reactive.calc
    def marker_color():
        vals = allzips[input.variable()]
        return col_numeric((vals.min(), vals.max()))

    # Redraw the map's data layers when the mode, the variable, or (in marker
    # mode) the visible zips change. zips_in_bounds() is only read in marker
    # mode, so panning zoomed out doesn't churn the heatmap.
    @reactive.effect
    def _():
        w = map.widget
        if w is None:
            return
        for layer in [
            x for x in w.layers if x.name == "heatmap" or x.name.startswith("marker-")
        ]:
            w.remove(layer)
        if show_markers():
            zips = zips_in_bounds()
            colors = marker_color()(zips[input.variable()])
            for (_, row), color in zip(zips.iterrows(), colors):
                w.add(create_marker(row, color))
        else:
            w.add(heatmap_layer())

    # ---------------------------------------------------------------------
    # Selected zip (click a marker) -> overlay + density-plot markers
    # ---------------------------------------------------------------------

    zip_selected: reactive.Value[pd.Series | None] = reactive.value(None)

    def create_marker(row: pd.Series, color: str) -> leaf.CircleMarker:
        marker = leaf.CircleMarker(
            location=(row.Lat, row.Long),
            radius=8,
            color=color,
            fill_color=color,
            fill_opacity=0.7,
            opacity=0.9,
            name=f"marker-{row.Zipcode}",
        )

        def _on_click(**kwargs):
            zip_selected.set(row)

        marker.on_click(_on_click)
        return marker

    @render.ui
    def selected_zip():
        row = zip_selected()
        if row is None:
            return None
        return ui.div(
            ui.div(f"{row.City}, {row.State} {row.Zipcode:05d}", class_="fw-semibold"),
            ui.div(f"Score {row.Score:.1f} · {row.College:.1f}% college educated"),
            ui.div(f"${row.Income:.0f}k median income · {row.Population:,} people"),
            ui.input_action_link("clear_zip", "Clear selection", class_="small"),
            class_="selected-zip",
        )

    @reactive.effect
    @reactive.event(input.clear_zip)
    def _():
        zip_selected.set(None)

    # ---------------------------------------------------------------------
    # Density plots: overall (black) vs in bounds (green)
    # ---------------------------------------------------------------------

    @render_plotly
    def density_score():
        return density_plot(
            allzips,
            zips_in_bounds(),
            selected=zip_selected(),
            var="Score",
            title="Overall Score",
            showlegend=True,
        )

    @render_plotly
    def density_college():
        return density_plot(
            allzips, zips_in_bounds(), selected=zip_selected(), var="College"
        )

    @render_plotly
    def density_income():
        return density_plot(
            allzips, zips_in_bounds(), selected=zip_selected(), var="Income"
        )

    @render_plotly
    def density_pop():
        return density_plot(
            allzips,
            zips_in_bounds(),
            selected=zip_selected(),
            var="Population",
            title="log10(Population)",
        )

    # ---------------------------------------------------------------------
    # Data explorer tab: the in-view zips as a grid, with a locator map
    # ---------------------------------------------------------------------

    @render.ui
    def data_intro():
        zips = zips_in_bounds()
        req(not zips.empty)
        return ui.div(
            ui.markdown(
                f"""
                {zips.shape[0]} zip codes are currently within the map's viewport, and amongst them:

                  * {100 * zips.Superzip.mean():.1f}% are superzips
                  * Mean income is ${zips.Income.mean():.0f}k  💰
                  * Mean population is {zips.Population.mean():.0f} 👨🏽👩🏽👦🏽
                  * Mean college educated is {zips.College.mean():.1f}% 🎓

                Use the filter controls on the table's columns to drill down further or
                click on a row to locate the zip on the map below.
                """
            ),
            class_="my-3 lead",
        )

    @render.data_frame
    def zips_data():
        return render.DataGrid(zips_in_bounds(), selection_mode="row")

    @reactive.calc
    def selected_row() -> pd.Series:
        sel = zips_data.cell_selection()
        req(sel["rows"])
        return zips_data.data().iloc[sel["rows"][0]]

    @render_ipyleaflet
    def table_map():
        return create_map()

    @reactive.effect
    @reactive.event(selected_row)
    def _():
        w = table_map.widget
        if w is None:
            return
        for layer in [x for x in w.layers if x.name.startswith("marker-")]:
            w.remove(layer)
        w.add(create_marker(selected_row(), color=GRID_MARKER_COLOR))


app = App(app_ui, server)
