import flet as ft
import requests
from helpers.roles import Roles

import flet as ft

class UsersSettings:
    def __init__(self, page: ft.Page):
        self.page = page
        self.base_url = self.page.session.store.get('api_base_url')
        self.token = self.page.session.store.get('token')
        self.selected_user_id = None

        self.user_roles = [
            'toti',
            Roles.USER, 
            Roles.PROPRIETAR, 
            Roles.CENZOR,
            Roles.ADMINISTRATOR, 
            Roles.PRESEDINTE, 
            Roles.EXPERT,
            Roles.BA,
        ]

        self.all_roles_list = ft.ListView(
            controls=self.create_list(self.user_roles, self.on_role_btn_click),
            spacing=10,
            width=350
        )
        self.all_users = self.get_all_users()
        self.role_users = ft.ListView(
            controls=self.create_users_list(self.all_users, self.on_user_btn_click),
            spacing=10,
            expand=True
        )

        self.placeholder = ft.Container(
            margin=ft.Margin.only(top=5),
            content=self.role_users,
            expand=True
        )

        self.email = ft.TextField(label="Email", read_only=True, expand=True)
        self.first_name = ft.TextField(label="Prenume", expand=True)
        self.last_name = ft.TextField(label = "Nume", expand=True)
        self.address = ft.TextField(label="Adresa", expand=True)
        self.profession = ft.TextField(label="Profesie", expand=True)
        self.role = ft.RadioGroup(
            content=ft.Row(
                [ft.Radio(value=role, label=role.upper()) for role in self.user_roles if role != "toti"]
            )
        )
        self.status = ft.TextField(label="Status", expand=True)
        self.profile_pic = ft.TextField(label="Poza profil", read_only=True, expand=True)
        self.created_at = ft.TextField(label="Data creare cont",read_only=True, expand=True)
        self.active = ft.TextField(label="Active: 0-Nu, 1-Da", expand=True)
        self.error = ft.Text(color=ft.Colors.RED)

        self.user_details = ft.Column(
            [
                ft.Text("Detalii utilizator", weight=ft.FontWeight.BOLD),
                self.email,
                self.first_name,
                self.last_name,
                self.address,
                self.profession,
                ft.Text("Rol:", weight=ft.FontWeight.BOLD),
                self.role,
                #self.status,
                #self.profile_pic,
                self.active,
                self.created_at,
                self.error,
                ft.Row(
                    [
                        ft.FilledButton("Salveaza", on_click=self.on_save_btn_click)
                    ],
                    alignment=ft.MainAxisAlignment.CENTER
                ),
                ft.Text()
            ],
            scroll=ft.ScrollMode.ADAPTIVE
        )

        self.search_bar = ft.TextField(
            label="Cauta", 
            on_submit=self.on_search_bar_submit, 
            expand=True
        )

    def on_role_btn_click(self, role):
        self.placeholder.content = self.role_users
        self.placeholder.update()
        self.role_users.controls.clear()
        users = self.users_by_role(role) if role != 'toti' else self.all_users
        self.role_users.controls = self.create_users_list(users, self.on_user_btn_click)
        self.role_users.update()

    def on_user_btn_click(self, user):
        self.selected_user_id = user['id']
        self.email.value = user['email']
        self.first_name.value = user['first_name']
        self.last_name.value = user['last_name']
        self.address.value = user['address']
        self.profession.value = user['profession']
        self.role.value = user['role']
        self.status.value = user['status']
        self.profile_pic.value = user['profile_pic']
        self.active.value = str(user['active'])
        self.created_at.value = user['created_at']
        self.error.value = ""
        self.placeholder.content = self.user_details
        self.placeholder.update()
        
    def create_list(self, items, on_click_handler):
        return [
            ft.Container(
                content=ft.Row(
                    [

                        ft.Row(
                            [
                                ft.Icon(ft.Icons.ARROW_RIGHT, size=20),
                                ft.Text(value=item.upper())
                            ]
                        ),
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
                ),
                expand=True,
                bgcolor=ft.Colors.BLUE_50,
                border = ft.Border.all(1, ft.Colors.GREY),
                padding=10,
                border_radius=8,
                ink=True,
                on_click=lambda e, cid=item: on_click_handler(cid)
            )
            for item in items
        ]
    
    def create_users_list(self, items, on_click_handler):
        return [
            ft.Container(
                content=ft.Row(
                    [

                        ft.Row(
                            [
                                ft.Icon(ft.Icons.ARROW_RIGHT, size=20),
                                ft.Text(value=item['email'])
                            ]
                        ),
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
                ),
                expand=True,
                bgcolor=ft.Colors.BLUE_50,
                border = ft.Border.all(1, ft.Colors.GREY),
                padding=10,
                border_radius=8,
                ink=True,
                on_click=lambda e, cid=item: on_click_handler(cid)
            )
            for item in items
        ]
    
    def get_all_users(self):
        payload = {}
        response = requests.get(
            f"{self.base_url}/users/",
            json=payload,
            headers={'Authorization': f'Bearer {self.token}'}
        )
        print(response.text)
        return response.json()

    def users_by_role(self, role):
        users = []
        for user in self.all_users:
            if user['role']==role:
                users.append(user)
        print(users)
        return users
    
    def on_save_btn_click(self, e):
        if self.selected_user_id is None:
            return

        payload = {
            "first_name": self.first_name.value,
            "last_name": self.last_name.value,
            "address": self.address.value,
            "profession": self.profession.value,
            "role": self.role.value,
            "status": self.status.value,
            "active": int(self.active.value) if str(self.active.value).isdigit() else 1
        }

        response = requests.put(
            f"{self.base_url}/users/update/{self.selected_user_id}",
            json=payload,
            headers={'Authorization': f'Bearer {self.token}'}
        )

        if response.status_code == 200:
            self.error.value = "Modificări salvate cu succes!"
            self.error.color = ft.Colors.GREEN
            self.all_users = self.get_all_users() # Refresh lista locală
        else:
            self.error.value = response.json().get("error", "Eroare la salvarea datelor")
            self.error.color = ft.Colors.RED
        
        self.error.update()

    def on_search_bar_submit(self, e):
        search = self.search_bar.value
        self.placeholder.content = self.role_users
        self.placeholder.update()
        self.role_users.controls.clear()
        users = [user for user in self.all_users if search in user['email']]
        self.role_users.controls = self.create_users_list(users, self.on_user_btn_click)
        self.role_users.update()


    def build(self):
        return ft.Container(
            content=ft.Column(
                [
                    ft.Row(
                        [
                            self.all_roles_list,
                            ft.VerticalDivider(width=1),
                            ft.Container(
                                content = ft.Column(
                                    [
                                        ft.Row(
                                            [
                                                self.search_bar
                                            ]
                                        ),
                                        #ft.Divider(height=1),
                                        self.placeholder
                                    ],
                                    expand=True
                                ),
                                padding=5,
                                expand=True
                            )
                        ],
                        expand=True
                    )
                ],
                expand=True
            ),
            expand=True
        )