import flet as ft
import requests
import time
from config import API_BASE_URL
import re
from pages.dashboard_page import DashboardPage

class TemporaryPassword:
    def __init__(self, page: ft.Page):
        self.page = page
        self.password = ft.TextField(label="Password", password=True, can_reveal_password=True, width=300)
        self.confirm_password = ft.TextField(label="Confirm Password", password=True, can_reveal_password=True, width=300)
        self.message = ft.Text("", color=ft.Colors.RED, text_align=ft.TextAlign.CENTER)

    def on_save_btn_click(self, e):
        # Password strength validation
        if len(self.password.value) < 8 or not re.search(r"[A-Z]", self.password.value) or not re.search(r"[0-9]", self.password.value):
            self.message.value = "Password must be at least 8 characters long and include a number and a capital letter"
            self.message.update()
            return
        # Placeholder for register logic
        if self.password.value != self.confirm_password.value:
            self.message.value = "Passwords do not match"
            self.message.update()
            return
        try:
            token = self.page.client_storage.get("token")
            headers = {"Authorization": f"Bearer {token}"}
            response = requests.post(f"{API_BASE_URL}/auth/temporary_password", headers=headers, json={
                "password": self.password.value
            })
            if response.status_code == 200:
                self.message.color = ft.Colors.GREEN
                self.message.value = "Password updated!\nYou will be redirected to Dashboard"
                self.message.update()
                time.sleep(3)
                # Proceed to Dashboard
                self.page.go("/dashboard") 
            else:
                self.message.color = ft.Colors.RED
                self.message.value = response.json().get("message", "Password update fail!")
                self.message.update()
        except Exception as e:
            print(e)

    def build(self):
        return ft.Container(
            content=ft.Column(
                [
                    ft.Text("This is your first login,\nplease change your password!", weight=ft.FontWeight.BOLD, size=20, text_align=ft.TextAlign.CENTER),
                    self.password,
                    self.confirm_password,
                    self.message,
                    ft.Button("Save", width=150, on_click=self.on_save_btn_click)
                ],
                horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                alignment=ft.MainAxisAlignment.CENTER,
                spacing=20,
            )
        )