import flet as ft
from pages.auth.register import Register
from dbActions.users import Users
from pages.auth.forgot_password import ForgotPassword

class Login:
    def __init__(self, page: ft.Page, auth):
        self.page = page
        self.auth = auth
        self.user_manager = Users()
        self.email = ft.TextField(label="E-mail")
        self.password = ft.TextField(label="Parola", password=True, can_reveal_password=True)
        self.error_message = ft.Text("", color=ft.Colors.RED)
        self.register = Register(self.page, self.auth, self)

    def on_login_btn_click(self, e):
        try:
            email = self.email.value
            password = self.password.value
            password_hash = self.user_manager.hash_password(password)
            user = self.user_manager.authenticate_user(email, password_hash)
            if user:
                self.page.client_storage.set("is_authenticated", True)
                self.page.session.set("user", user)
                self.error_message.value = ''
                self.error_message.update()
                if user['role'] == 'admin':
                    self.page.go('/admin')
                else: 
                    if user['name'] is None or len(user['name'])<=1:
                        self.page.go("/profil")
                    else:
                        self.page.go('/')
            else:
                self.error_message.value = 'E-mail sau parola sunt gresite!'
                self.error_message.update()
        except Exception as e:
            print("Unable to login, error: ", e)

    def on_register_btn_click(self, e):
        self.auth.placeholder.content = self.register.build()
        self.auth.placeholder.update()

    def on_forgot_password_btn_click(self, e):
        forgot_password = ForgotPassword(self.page, self.auth, self)
        self.auth.placeholder.content.clean()
        self.auth.placeholder.content = forgot_password.build()
        self.auth.placeholder.update()

    def build(self):
        return ft.Column(
            [
                self.email,
                self.password,
                self.error_message,
                ft.Row(
                    [
                        ft.Button("Autentificare", width=200, on_click=self.on_login_btn_click)
                    ],
                    alignment=ft.MainAxisAlignment.CENTER
                ),
                ft.Text(),
                ft.Row(
                    [
                        ft.TextButton("Creaza cont", on_click=self.on_register_btn_click),
                        ft.TextButton("Ai uitat parola?", on_click=self.on_forgot_password_btn_click)
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                )
            ]
        )