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

class Register:
    def __init__(self, page: ft.Page, auth, login):
        self.page = page
        self.auth = auth
        self.login = login
        self.email = ft.TextField(label="Email", width=300)
        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.name = ft.TextField(label="Company Name", width=300)
        self.register_button = ft.ElevatedButton(text="Register", on_click=self.on_register_clicked, width=150)
        self.back_button = ft.TextButton(text="Back to Login", on_click=self.on_back_clicked)
        self.message = ft.Text(value="", color=ft.Colors.RED)

    def on_register_clicked(self, e):
        # Email validation
        email_regex = r"^[^@]+@[^@]+\.[^@\.]+(\.[^@\.]+)*$"
        if not re.match(email_regex, self.email.value):
            self.message.value = "Invalid email address"
            self.page.update()
            return
        # 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.page.update()
            return
        # Placeholder for register logic
        if self.password.value != self.confirm_password.value:
            self.message.value = "Passwords do not match"
            self.page.update()
            return
        self.message.value = "Registering..."
        self.page.update()
        try:
            response = requests.post(f"{API_BASE_URL}/auth/register", json={
                "name": self.name.value,
                "email": self.email.value,
                "password": self.password.value
            })
            if response.status_code == 201:
                self.message.color = ft.Colors.GREEN
                self.message.value = "Registration successful. You can now log in."
                self.page.update()
                time.sleep(3)
                self.on_back_clicked('')
            else:
                self.message.color = ft.Colors.RED
                self.message.value = response.json().get("message", "Registration failed, the user is already registered.")
                self.page.update()
        except Exception as err:
            self.message.color = ft.Colors.RED
            self.message.value = f"Error: {err}"
            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(
                    "Register", 
                    size=30, 
                    weight="bold"
                ),
                self.name,
                self.email,
                self.password,
                self.confirm_password,
                self.register_button,
                self.message,
                self.back_button
            ],
            alignment=ft.MainAxisAlignment.CENTER,
            horizontal_alignment=ft.CrossAxisAlignment.CENTER
        )