import flet as ft
from pages.admin_tenants_page import Tenants
from pages.admin_subscriptions_page import Subscriptions
import requests
from config import API_BASE_URL

class Admin:
    def __init__(self, page: ft.Page):
        self.page = page
        self.placeholder = ft.Column(expand=True)
        self.total_tenants = ft.Text("Total tenants: 0")
        self.revenues = ft.Text("Total revenue: 0")

    def get_subscriptions(self):
        try:
            token = self.page.client_storage.get("token")
            headers = {"Authorization": f"Bearer {token}"}
            response = requests.get(f"{API_BASE_URL}/admin/subscriptions/", headers=headers)      
            return response.json() if response.status_code == 200 else []
        except Exception as e:
            print("Error loading clients:", e)

    def build_dashboard(self):
        all_subscriptions = self.get_subscriptions()
        total_tenants = len(all_subscriptions)
        self.total_tenants.value = f"Total tenants: {total_tenants}"
        sum = 0
        for subscription in all_subscriptions:
            if subscription['status'] == 'active':
                if subscription['plan'] == 'first_2_months':
                    sum += 0
                elif subscription['plan'] == 'monthly':
                    sum += 100
                elif subscription['plan'] == 'yearly':
                    sum += 1000
        self.revenues.value = f"Total revenue: {sum}"
        return ft.Row(
            [
                ft.Container(
                    content = ft.Column(
                        [
                            ft.Icon(name=ft.Icons.PEOPLE, size=50),
                            self.total_tenants,
                        ],
                        alignment=ft.MainAxisAlignment.CENTER,
                        horizontal_alignment=ft.CrossAxisAlignment.CENTER
                    ),
                    bgcolor=ft.Colors.BLUE_100,
                    border_radius=20,
                    padding=20
                ),
                ft.Container(
                    content = ft.Column(
                        [
                            ft.Icon(name=ft.Icons.AUTORENEW, size=50),
                            self.revenues,
                        ],
                        alignment=ft.MainAxisAlignment.CENTER,
                        horizontal_alignment=ft.CrossAxisAlignment.CENTER
                    ),
                    bgcolor=ft.Colors.BLUE_100,
                    border_radius=20,
                    padding=20
                ),
            ]
        )

    def on_tenants_btn_click(self, e):
        tenents = Tenants(self.page)
        self.placeholder.controls = [tenents.build()]
        self.placeholder.update()

    def on_subscription_btn_click(self, e):
        subscription = Subscriptions(self.page)
        self.placeholder.controls = [subscription.build()]
        self.placeholder.update()

    def on_dashboard_btn_click(self, e):
        self.placeholder.controls = [
            ft.Text("Admin Dashboard", size=24, weight=ft.FontWeight.BOLD),
            self.build_dashboard()
        ]
        self.placeholder.update()

    def on_logout_btn_click(self, e):
        self.page.client_storage.remove("token")
        self.page.session.clear()
        self.page.go("/auth")

    def build(self):
        self.placeholder.controls = [
            ft.Text("Admin Dashboard", size=24, weight=ft.FontWeight.BOLD),
            self.build_dashboard()
        ]
        return ft.Container(
            content= ft.Row(
                    [
                        ft.Column(
                            [
                                ft.Column(
                                    [
                                        ft.Button(
                                            "Dashboard",
                                            on_click=self.on_dashboard_btn_click,
                                            width=150, 
                                            icon=ft.Icons.DASHBOARD
                                        ),
                                        ft.Button(
                                            "Tenents",
                                            on_click= self.on_tenants_btn_click,
                                            width=150,
                                            icon=ft.Icons.PEOPLE
                                        ),
                                        ft.Button(
                                            "Subscriptions",
                                            on_click=self.on_subscription_btn_click,
                                            width=150,
                                            icon=ft.Icons.AUTORENEW
                                        )
                                    ]
                                ),
                                ft.Button(
                                    "Logout",
                                    on_click=self.on_logout_btn_click,
                                    width=150,
                                    icon=ft.Icons.LOGOUT
                                )
                            ],
                            alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
                            horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                            #width=180
                        ),
                        ft.VerticalDivider(),
                        ft.Container(
                            content=ft.Column(
                                [
                                    self.placeholder,
                                ]
                            ),
                            expand=True
                        )
                    ],
                    expand=True
                ),
            expand=True,
            padding=20
        )