import flet as ft
import requests
import json

class VerifyCode:
    def __init__(self, page: ft.Page, auth):
        self.page = page
        self.auth = auth
        self.code = ft.TextField(label="Codul de verificare primit pe email")
        self.verify_btn = ft.Button(
            "Verifica",
            on_click=self.on_verify_btn_click
        )
        self.error_message = ft.Text(color=ft.Colors.RED)

    async def on_verify_btn_click(self, e):
        code = self.code.value
        if len(self.code.value) > 0:
            API_BASE_URL = self.page.session.store.get('api_base_url')
            self.email = self.page.session.store.get('email')
            response = requests.post(f"{API_BASE_URL}/auth/verify_code", json={"email": self.email, "code": code})
            if response.status_code == 200:
                self.error_message.value = "Codul a fost verificat cu succes. Va puteti autentifica."
                token = response.json().get("access_token")
                self.page.session.store.set('token', token)
                response = requests.get(
                        f"{API_BASE_URL}/auth/me",
                        headers={"Authorization": f"Bearer {token}"},
                        timeout=10,
                    )
                user = json.loads(response.text)
                print(user)
                self.page.session.store.set('user', user)

                # Verificăm dacă utilizatorul a bifat "Keep me authenticated"
                keep_me = self.page.session.store.get('keep_me_authenticated')
                if keep_me == True or keep_me == "true":
                    await self.set_value("mi_user_id", user['id'])
                    await self.set_value("mi_tocken", token)

                self.page.go('/home')
            else:
                self.error_message.value = "Code invalid sau expirat!"
        else:
            self.error_message.value = "Code invalid sau expirat!"

    async def set_value(self, key, value):
        await ft.SharedPreferences().set(key, str(value))

    def build(self):
        return ft.Container(
            content=ft.Column(
                [
                    self.code, 
                    self.error_message,
                    self.verify_btn
                ],
                horizontal_alignment=ft.CrossAxisAlignment.CENTER
            )
        )