from __future__ import annotations

import pydantic
import state
from PyQt6.QtWidgets import (
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QMessageBox,
    QPushButton,
    QVBoxLayout,
    QWidget,
)
from request_client import RequestClient


class User(pydantic.BaseModel):
    user_id: int | None = None
    username: str
    email: str

    @staticmethod
    def get(user_id: int | None = None) -> User:
        params = {}
        if user_id:
            url = "/users"
            params["user_id"] = user_id
        else:
            url = "/users/current"
        response = RequestClient().client.get(url, params=params)
        if not response.is_success:
            QMessageBox.warning(None, "Error getting permissions", response.text)
            return
        return User.model_validate_json(response.text)

    @staticmethod
    def delete():
        if not RequestClient().client.delete("/users").is_success:
            raise Exception("Error deleting user")

    def put(self):
        response = RequestClient().client.put(
            "/users", json={"username": self.username, "email": self.email}
        )
        if not response.is_success:
            QMessageBox.warning(None, "Error updating user", response.text)
            return
        QMessageBox.information(None, "User updated", "User updated")


class UserSearch(User):
    similarity: float

    @staticmethod
    def search(search_str: str) -> list[UserSearch]:
        return pydantic.TypeAdapter(list[UserSearch]).validate_json(
            RequestClient()
            .client.get("/users/search", params={"search_string": search_str})
            .text
        )


class UserWidget(QWidget):
    def __init__(self, state: state.State):
        super().__init__()
        self.state = state
        self.setWindowTitle("User information")
        self.user = User.get()
        main_layout = QVBoxLayout()
        lines = [("username", self.user.username), ("email", self.user.email)]
        edits = []
        for line in lines:
            layout = QHBoxLayout()
            label = QLabel(line[0])
            edit = QLineEdit(line[1])
            layout.addWidget(label)
            layout.addWidget(edit)
            main_layout.addLayout(layout)
            edits.append(edit)
        self.username: QLineEdit = edits[0]
        self.email: QLineEdit = edits[1]
        button_layout = QHBoxLayout()
        buttons = [("Update", self.update_user), ("Delete", self.delete_user)]
        for text, func in buttons:
            button = QPushButton(text)
            button.clicked.connect(func)
            button_layout.addWidget(button)
        main_layout.addLayout(button_layout)
        self.setLayout(main_layout)

    def delete_user(self):
        User.delete()
        self.close()
        self.state.logout()

    def update_user(self):
        self.user.username = self.username.text()
        self.user.email = self.email.text()
        self.user.put()
