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

class ResetPasswordPage:
    def __init__(self, page: ft.Page):
        self.page = page
        self.page.update()
        self.token = None
        if '/reset_password?token=' in self.page.route:
            self.token = self.page.route.split('?token=')[1]
        self.password = ft.TextField(label="New Password", password=True, can_reveal_password=True)
        self.confirm_password = ft.TextField(label="Confirm Password", password=True, can_reveal_password=True)
        self.message = ft.Text("")
        self.submit_btn = ft.ElevatedButton("Reset Password", on_click=self.on_submit)

    def on_submit(self, e):
        new_password = self.password.value.strip()
        confirm_password = self.confirm_password.value.strip()

        # Password strength validation
        if len(new_password) < 8 or not re.search(r"[A-Z]", new_password) or not re.search(r"[0-9]", new_password):
            self.message.value = "Password must be at least 8 characters long and include a number and a capital letter."
            self.page.update()
            return

        if not new_password or not confirm_password:
            self.message.value = "Both fields are required."
        elif new_password != confirm_password:
            self.message.value = "Passwords do not match."
        elif len(new_password) < 6:
            self.message.value = "Password must be at least 6 characters."
        else:
            try:
                response = requests.post(
                    f"{API_BASE_URL}/auth/reset_password",
                    json={"token": self.token, "new_password": new_password},
                    timeout=10
                )
                if response.status_code == 200:
                    self.message.value = "Password reset successfully. Please login."
                else:
                    self.message.value = "Invalid or expired token."
            except Exception as ex:
                self.message.value = f"Request failed: {ex}"

        self.page.update()

    def build(self):
        return ft.Container(
            content=ft.Column(
                [
                    ft.Text("Reset Your Password", style=ft.TextThemeStyle.HEADLINE_MEDIUM),
                    self.password,
                    self.confirm_password,
                    self.message,
                    self.submit_btn
                ],
                alignment=ft.MainAxisAlignment.CENTER,
                horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                expand=True,
            ),
            expand=True,
            alignment=ft.alignment.center,
            padding=20,
            width=350
        )