import flet as ft
import requests
from config import API_BASE_URL
from pages.temporary_password_page import TemporaryPassword

class TwoFactorAuth:
    def __init__(self, page: ft.Page, email: str, login, auth):
        self.page = page
        self.email = email
        self.auth = auth
        self.login = login
        self.code_field = ft.TextField(label="Verification Code")
        self.error_text = ft.Text(value="", color=ft.Colors.RED)
        self.success_text = ft.Text(value="", color=ft.Colors.GREEN)
        self.verify_button = ft.ElevatedButton(text="Verify", on_click=self.on_verify_click, width=150)
        self.back_button = ft.TextButton(text="Back to Login", on_click=self.on_back_clicked)

    def on_verify_click(self, e):
        code = self.code_field.value

        if not code:
            self.error_text.value = "Please enter the verification code."
            self.page.update()
            return

        try:
            response = requests.post(f"{API_BASE_URL}/auth/verify_code", json={"email": self.email, "code": code})
            if response.status_code == 200:
                token = response.json().get("access_token")
                self.page.client_storage.set("token", token)
                user_info = requests.get(f"{API_BASE_URL}/auth/me", headers={"Authorization": f"Bearer {token}"}).json()
                self.page.session.set("user_id", user_info.get("id"))
                self.page.session.set("first_order_number", user_info['first_order_number'])
                #print(user_info.get("user_role"))
                if user_info.get("user_role") == 'admin':
                    print('Admin Logged In')
                    self.page.go("/admin")
                else:
                    ui = requests.get(
                        f"{API_BASE_URL}/auth/me",
                        headers={"Authorization": f"Bearer {token}"},
                        timeout=10,
                    )

                    if ui.status_code == 200:
                        uj = ui.json()
                        try:
                            logo_filename = uj.get("logo_filename", "")
                            if logo_filename:
                                self.page.client_storage.set("custom_logo", logo_filename)
                        except Exception:
                            pass
                    if uj['temporary_password'] == 1:
                        self.auth.placeholder.content.clean()
                        temp_passwd_page = TemporaryPassword(self.page)
                        self.auth.placeholder.content = temp_passwd_page.build()
                        self.auth.placeholder.update()
                    else:
                        self.success_text.value = "Verification successful. You are now logged in."
                        self.error_text.value = ""
                        self.page.update()
                        self.page.go("/dashboard")  
            else:
                self.error_text.value = "Invalid or expired code."
                self.success_text.value = ""
                self.page.update()
        except Exception as err:
            self.error_text.value = f"Error: {err}"
            self.success_text.value = ""
            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(value=f"Enter the code sent to {self.email}", size=18),
                    self.code_field,
                    self.verify_button,
                    self.error_text,
                    self.success_text,
                    self.back_button
                ],
                horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                alignment=ft.MainAxisAlignment.CENTER,
                spacing=20,
                width=350
            )