import flet as ft
from helpers.emails import send_gmail
from helpers.validations import Validations
import requests
import string
import secrets
import os

class ForgotPassword:
    def __init__(self, page: ft.Page, login, auth):
        self.page = page
        self.login = login
        self.auth = auth
        self.email = ft.TextField(label="E-mail", expand=True)
        self.code = ft.TextField(label="Codul de securitate", expand=True)
        self.password = ft.TextField(label="Parola", password=True, can_reveal_password=True, expand=True)
        self.confirm_password = ft.TextField(label="Confirmați parola", password=True, can_reveal_password=True, expand=True)
        self.error_message = ft.Text(color=ft.Colors.RED)
        self.inserted_code = ft.TextField(label="Codul de verificare primit pe email", expand=True)

        self.otp_code = self._generate_numeric_code()
        self.validate = Validations(self.error_message, self.page)

        self.title = ft.Text(
            "Ai uitat parola?",
            text_align=ft.TextAlign.CENTER, 
            size=20, 
            weight=ft.FontWeight.BOLD,
            width=350
        )

        self.main_column = ft.Column(
            [
                self.title,
                self.email,
                self.error_message,
                ft.Button("Recupereaza parola", on_click=self.send_code_on_email),
            ],
            horizontal_alignment=ft.CrossAxisAlignment.CENTER
        )
        self.go_to_login = ft.TextButton("Mergeti la autentificare", on_click=self.on_go_to_login_btn_click, width=350)

        self.page_column = ft.Column(
            [
                self.main_column,
                ft.Text(),
                self.go_to_login
            ]
        )

    def _generate_numeric_code(self) -> str:
        digits = string.digits 
        return ''.join(secrets.choice(digits) for _ in range(6))
    
    def send_code_on_email(self, e):
        if self.validate.is_valid_email(self.email.value):
            self.main_column.controls.clear()
            self.main_column.controls.append(self.title)
            self.main_column.controls.append(self.inserted_code)
            self.main_column.controls.append(self.error_message)
            self.main_column.controls.append("Verifica", width=150, on_click=self.verfy_code)
            self.main_column.update()
            #print(self.otp_code)
            send_gmail(
                to_email=self.email.value,
                subject="Cod de verificare",
                body=f"Codul tau de verificare este: {self.otp_code}"
            ) 

    def verfy_code(self, e):
        inserted_code = self.inserted_code.value
        if inserted_code == self.otp_code:
            self.main_column.controls.clear()
            self.main_column.controls.append(self.title)
            self.main_column.controls.append(self.password)
            self.main_column.controls.append(self.confirm_password)
            self.main_column.controls.append(self.error_message)
            self.main_column.controls.append(
                ft.Button("Salveaza", width=150, on_click=self.on_save_btn_click)
            )
            self.error_message.value = ''          
        else:
            self.error_message.value = "Code invalid sau expirat!"
            print(inserted_code)
            print(self.otp_code)
    
    def on_go_to_login_btn_click(self, e):
        self.auth.placeholder.content = self.login.build()

    def on_save_btn_click(self, e):
        password = self.password.value
        repeat_password = self.confirm_password.value
        if self.validate.is_password_strong(password):
            if self.validate.check_repeat_password(password, repeat_password):
                base_url = self.page.session.store.get('api_base_url')
                token = os.getenv('PASSWORD_TOKEN')
                response = requests.post(f'{base_url}/auth/update_passwrod', json={"email": self.email.value, "password": password, "token": token})
                if response.status_code == 200:
                    self.error_message.value = 'Parola a fost salvata cu succes. Acum va puteti autentifica!'
                    self.error_message.color = ft.Colors.GREEN
                    self.error_message.update()

                    self.page_column.controls.clear()
                    self.page_column.controls.append(self.title)
                    self.page_column.controls.append(self.error_message)
                    self.page_column.controls.append(self.go_to_login)
                    self.go_to_login.content = "Mergeti la autentificare"
                else: 
                    self.error_message.value = 'Recuperarea parolei a esuat. Va rugam conactati administratorul.'
                    self.error_message.color = ft.Colors.RED
                    self.error_message.update()

    def build(self):
        return self.page_column
    
        