import flet as ft
from auth.login import *

USERNAME = "admin"
PASSWORD = "1234"


def generate_key():
    if not os.path.exists(KEY_FILE):
        key = Fernet.generate_key()
        with open(KEY_FILE, "wb") as f:
            f.write(key)


async def load_fernet():
    with open(KEY_FILE, "rb") as f:
        key = f.read()
    return Fernet(key)


async def main(page: ft.Page):
    generate_key()
    fernet = await load_fernet()

    page.title = "SClient"
    page.window_width = 400
    page.window_height = 300
    page.vertical_alignment = ft.MainAxisAlignment.CENTER

    login_input = ft.TextField(label="Логин", autofocus=True)
    password_input = ft.TextField(label="Пароль", password=True, can_reveal_password=True)
    remember_checkbox = ft.Checkbox(label="Запомнить меня")
    status_text = ft.Text(color=ft.Colors.RED)

    if os.path.exists(REMEMBER_FILE):
        try:
            with open(REMEMBER_FILE, "rb") as f:
                lines = f.readlines()
                if len(lines) == 2:
                    saved_login = lines[0].decode().strip()
                    encrypted_pw = lines[1].strip()
                    decrypted_pw = fernet.decrypt(encrypted_pw).decode()

                    login_input.value = saved_login
                    password_input.value = decrypted_pw
                    remember_checkbox.value = True
        except Exception as e:
            print(f"[ОШИБКА] Не удалось прочитать данные: {e}")

    async def login_click(e):
        if await login(login_input.value, password_input.value):
            if remember_checkbox.value:
                encrypted_pw = fernet.encrypt(password_input.value.encode())
                with open(REMEMBER_FILE, "wb") as f:
                    f.write(f"{login_input.value}\n".encode())
                    f.write(encrypted_pw)
            else:
                if os.path.exists(REMEMBER_FILE):
                    os.remove(REMEMBER_FILE)

            page.clean()
            page.add(
                ft.Column(
                    [
                        ft.Text(f"Добро пожаловать, {USERNAME}!", size=24),
                        ft.ElevatedButton("Выйти", on_click=lambda e: page.go("/"))
                    ],
                    alignment=ft.MainAxisAlignment.CENTER,
                    horizontal_alignment=ft.CrossAxisAlignment.CENTER
                )
            )
        else:
            status_text.value = "Неверный логин или пароль"
            page.update()

    page.add(
        ft.Container(
            content=ft.Column(
                controls=[
                    ft.Image(
                        src="sonoma.png",
                        width=50,
                        height=50,
                        fit=ft.ImageFit.CONTAIN
                    ),
                    ft.Text("SClient", size=24, weight=ft.FontWeight.BOLD),
                    login_input,
                    password_input,
                    remember_checkbox,
                    ft.ElevatedButton("Войти", on_click=login_click),
                    status_text
                ],
                width=300,
                alignment=ft.MainAxisAlignment.CENTER,
                horizontal_alignment=ft.CrossAxisAlignment.CENTER
            ),
            alignment=ft.alignment.center,
            expand=True
        )
    )

ft.app(main)
