from kivy.app import App
from kivy.uix.image import Image
from kivy.graphics.texture import Texture
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.lang import Builder

import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg

import pandas as pd
from io import BytesIO
from PIL import Image as PILImage


class GraphScreen(Screen):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.graph_texture = None

    def on_enter(self):
        # Sample CoinGecko-style data
        data = {
            "prices": [
                [1711843200000, 69702.31],
                [1711929600000, 71246.95],
                [1711983682000, 68887.75]
            ]
        }

        df = pd.DataFrame(data["prices"], columns=["timestamp", "price"])
        df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")

        # Plot
        fig, ax = plt.subplots()
        ax.plot(df["timestamp"], df["price"], label="Price", color="green")
        ax.set_title("Price Over Time")
        ax.set_xlabel("Date")
        ax.set_ylabel("Price (USD)")
        ax.legend()

        # Convert plot to Kivy texture
        canvas = FigureCanvasAgg(fig)
        canvas.draw()
        buf = BytesIO()
        fig.savefig(buf, format='png')
        buf.seek(0)

        pil_image = PILImage.open(buf).transpose(PILImage.FLIP_TOP_BOTTOM)
        tex = Texture.create(size=pil_image.size, colorfmt='rgba')
        tex.blit_buffer(pil_image.convert('RGBA').tobytes(), colorfmt='rgba', bufferfmt='ubyte')
        tex.flip_vertical()

        # Access the image widget via ids correctly
        self.graph_texture = tex


class MyApp(App):
    def build(self):
        return Builder.load_file('example_graph_code.kv')

if __name__ == "__main__":
    app = MyApp()
    app.run()