import flet as ft
from pages.auth_page import Auth
from pages.dashboard_page import DashboardPage
from pages.admin_page import Admin
from pages.reset_password_page import ResetPasswordPage
import os
import requests
from config import API_BASE_URL, FLET_SERVER_PORT

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

def main(page: ft.Page):
    page.title = "Transport Manager"
    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

    def is_token_valid(token: str) -> bool:
        if not token:
            return False
        try:
            resp = requests.get(
                f"{API_BASE_URL}/auth/validate_token",
                headers={"Authorization": f"Bearer {token}"},
                timeout=5,
            )
            return resp.status_code == 200
        except Exception:
            # If the server can't be reached, treat as invalid to avoid granting access
            return False

    def route_change(e):
        # Current path
        route = page.route

        # Determine auth state by validating token with backend
        token = page.client_storage.get("token") 
        valid_token = is_token_valid(token) if token else False
        is_authenticated = bool(valid_token and page.session.get('user_id'))

        # If token is invalid but present, clean it up
        if token and not valid_token:
            try:
                page.client_storage.remove("token")
            except Exception:
                pass
            try:
                page.session.pop("user_id", None)
            except Exception:
                pass

        # Clear current UI
        page.controls.clear()

        # 1) Reset Password – allow opening directly from email link
        if route and "reset_password" in route:
            reset_page = ResetPasswordPage(page)
            page.add(reset_page.build())
            page.update()
            return

        # 2) Auth route – if already logged in with a valid token, go to dashboard
        if route == "/auth":
            if is_authenticated:
                page.go("/dashboard")
                return
            login = Auth(page)
            page.add(login.build())
            page.update()
            return

        # 3) Admin (protect)
        if route == "/admin":
            if not is_authenticated:
                page.go("/auth")
                return
            admin = Admin(page)
            page.add(admin.build())
            page.update()
            return

        # 4) Dashboard & root
        if route in ("/dashboard", "/", None):
            if not is_authenticated:
                page.go("/auth")
                return
            dashboard = DashboardPage(page)
            page.add(dashboard.build())
            page.update()
            return

        # 5) Fallback 404
        page.add(ft.Text("404: Page not found"))
        page.update()

    page.on_route_change = route_change
    page.go(page.route or "/auth")

ft.app(
    target=main,
    assets_dir="assets",
    upload_dir="uploads",
    view=ft.WEB_BROWSER,
    host="0.0.0.0",
    port=FLET_SERVER_PORT,
)