import asyncio

import flet as ft
from pages.auth.auth import Auth
from pages.dashboard.home import Home

import os
os.environ["FLET_SECRET_KEY"] = os.urandom(12).hex()
os.environ['PASSWORD_TOKEN'] = os.urandom(12).hex()

import requests, json

async def main(page: ft.Page):
    page.title = "Administarare locuintelor in mod eficient"
    page.theme_mode = ft.ThemeMode.LIGHT
    page.theme = ft.Theme(
        color_scheme=ft.ColorScheme(
            primary=ft.Colors.BLUE
        )
    )
    page.vertical_alignment = ft.MainAxisAlignment.CENTER
    page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
    page.padding = 0
    page.web = True
    
    async def route_change():
        page.controls.clear()
        route = page.route
        print(route)

        #set backend url
        page.session.store.set('api_base_url', 'http://localhost:5000')

        if route == "/auth":
            login = Auth(page)
            page.add(login.build())
            return
        
        if route =="/home" or "/":
            token = page.session.store.get('token')
            user = page.session.store.get('user')

            # Dacă nu avem sesiune activă, verificăm stocarea persistentă
            if not token or not user:
                token = await get_value("mi_tocken")
                if not token:
                    await page.push_route('/auth')
                    return
                
                API_BASE_URL = page.session.store.get('api_base_url')
                try:
                    response = requests.get(
                        f"{API_BASE_URL}/auth/me",
                        headers={"Authorization": f"Bearer {token}"},
                        timeout=10,
                    )
                    if response.status_code == 200:
                        user = response.json()
                        page.session.store.set('token', token)
                        page.session.store.set('user', user)
                    else:
                        await page.push_route('/auth')
                        return
                except Exception:
                    await page.push_route('/auth')
                    return

            home = Home(page)
            page.add(await home.build())
            page.update()
            return
        
        page.add(ft.Text("404: Page not found"))
        
    async def get_value(key):
        return await ft.SharedPreferences().get(key)
    
    page.on_route_change = route_change
    await page.push_route('/home')

ft.run(
    main = main,
    assets_dir = "assets",
    upload_dir = "assets/uploads",
    view=ft.AppView.WEB_BROWSER,
    port=8090,
    host="0.0.0.0"
)