from typing import TypedDict
import os
import numpy as np
import reflex as rx
import reflex_xy as rxy
import xy
from xy_colorsets import categorical_colors, legend_style, theme

PALETTE = os.environ.get("XY_CAP_PALETTE", "colorset1")
COLORS = categorical_colors(PALETTE, 3)

def fixed_chart():
    return xy.chart(xy.scatter([0.,1.,2.,3.], [2.,4.,3.,5.], color=COLORS[0], size=8, opacity=1, density=False),
                    xy.line([0.,1.,2.,3.], [2.,4.,3.,5.], color=COLORS[1], width=3),
                    xy.x_axis(label="Sample"), xy.y_axis(label="Reading"),
                    xy.legend(show=False), xy.interaction_config(click=True,select=True),
                    theme(PALETTE), title="Fixed source", width="100%", height=300)

STATIC = fixed_chart()
LIVE = rxy.inline(fixed_chart())

class CloudColumns(TypedDict):
    x: np.ndarray
    y: np.ndarray

class Dashboard(rx.State):
    points: int = 8
    next_x: int = 4
    message: str = "Click a live point"
    selected_count: int = 0

    @rxy.data
    def cloud(self) -> CloudColumns:
        x = np.arange(self.points, dtype=float)
        return {"x": x, "y": 3 + np.sqrt(x + 1)}

    @rxy.figure(probe="figure")
    def dynamic(self) -> xy.Chart:
        x = np.arange(self.points, dtype=float)
        marks = [xy.scatter(x, 2 + x * .8, color=COLORS[0], size=8, opacity=1, density=False)]
        if self.points > 8:
            marks.append(xy.hline(6, color=COLORS[1]))
        return xy.chart(*marks, xy.legend(show=False), theme(PALETTE),
                        xy.x_axis(label="Sample"), xy.y_axis(label="Reading"),
                        title="State-dependent structure", width="100%", height=300)

    @rx.event
    def add_points(self):
        self.points += 2

    @rx.event
    def stream(self):
        rxy.append(LIVE, x=[float(self.next_x)], y=[float(self.next_x % 4 + 2)])
        rxy.append(LIVE, x=[float(self.next_x)], y=[float(self.next_x % 4 + 2)], trace=1)
        self.next_x += 1

    @rx.event
    def clicked(self, event: rxy.PointClickEvent):
        point = event.get("data") or {}
        self.message = f"Canonical row {event.get('canonical_row_id')}: x={point.get('x')}, y={point.get('y')}"

    @rx.event
    def selected(self, event: rxy.SelectEndEvent):
        selection = rxy.resolve_selection(event)
        self.selected_count = len(selection) if selection is not None else 0

    @rx.event
    def hovered(self, event: rxy.PointHoverEvent):
        self.message = f"Hover canonical row {event.get('canonical_row_id')}"

    @rx.event
    def viewed(self, event: rxy.ViewChangeEvent):
        if event.get("phase") == "final":
            self.message = f"Final view: {event.get('x_domain')}"

def index() -> rx.Component:
    return rx.vstack(
        rx.heading("XY host boundaries"),
        rx.text("Static payload: browser interactions only; no Python event dispatch."),
        rxy.chart(STATIC, height="300px", width="100%"),
        rx.text("Inline handle: shared fixed data with live canonical events and append."),
        rxy.chart(LIVE, on_point_click=Dashboard.clicked, on_point_hover=Dashboard.hovered,
                  on_select_end=Dashboard.selected, on_view_change=Dashboard.viewed,
                  height="300px", width="100%"),
        rx.button("Append one point", on_click=Dashboard.stream, background=COLORS[0], color="#ffffff"),
        rx.text(Dashboard.message), rx.text("Selected rows: ", Dashboard.selected_count),
        rx.text("State data: column arrays change while the chart structure stays fixed."),
        rxy.chart(xy.scatter("x", "y", color=COLORS[0], size=8, opacity=1, density=False),
                  xy.legend(show=False), theme(PALETTE), data=Dashboard.cloud,
                  height="300px", width="100%"),
        rx.text("State figure: adding observations also adds a reference mark."),
        rxy.chart(figure=Dashboard.dynamic, height="300px", width="100%"),
        rx.button("Add two state observations", on_click=Dashboard.add_points, background=COLORS[0], color="#ffffff"),
        width="100%", max_width="1000px", padding="24px", spacing="4", background="#f7f7f7", color="#000000",
    )

app = rx.App()
app.add_page(index)
