import flet as ft
import re
import requests
from config import API_BASE_URL

class ForgotPassword:
    def __init__(self, page: ft.Page, auth, login):
        self.page = page
        self.auth = auth
        self.login = login
        self.email = ft.TextField(label="Email")
        self.error = ft.Text("", color=ft.Colors.RED)
        self.success = ft.Text("", color=ft.Colors.GREEN)
        self.back_button = ft.TextButton(text="Back to Login", on_click=self.on_back_clicked)

    def on_submit(self, e):
        email_value = self.email.value.strip()
        email_regex = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$"

        if not re.match(email_regex, email_value):
            self.error.value = "Please enter a valid email address."
            self.success.value = ""
        else:
            try:
                response = requests.post(
                    f"{API_BASE_URL}/auth/forgot_password",
                    json={"email": email_value},
                    timeout=10
                )
                if response.status_code == 200:
                    self.success.value = "If the email exists, you will receive a reset link shortly."
                    self.error.value = ""
                else:
                    self.error.value = "Server error. Please try again later."
                    self.success.value = ""
            except Exception as ex:
                self.error.value = "Connection error. Please check your internet."
                self.success.value = ""
                print(ex)

        self.page.update()
    
    def on_back_clicked(self, e):
        self.auth.placeholder.content.clean()
        self.auth.placeholder.content = self.login.build()
        self.auth.placeholder.update()

    def build(self):
        return ft.Column(
                [
                    ft.Text("Forgot Password", size=30, weight="bold"),
                    self.email,
                    ft.ElevatedButton("Reset Password", on_click=self.on_submit, width=150),
                    self.error,
                    self.success,
                    self.back_button,
                ],
                horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                alignment=ft.MainAxisAlignment.CENTER,
                spacing=20,
                width=350
            )