extends Control

@onready var net: Node = get_node_or_null("/root/NetAPI")
@onready var gm: Node = get_node_or_null("/root/GameManager")

var status_label: Label
var username_edit: LineEdit
var password_edit: LineEdit
var btn_login: Button
var btn_register: Button
var btn_back: Button

func _ready() -> void:
	_build_ui()
	_set_status("")

func _build_ui() -> void:
	anchor_left = 0
	anchor_top = 0
	anchor_right = 1
	anchor_bottom = 1
	offset_left = 0
	offset_top = 0
	offset_right = 0
	offset_bottom = 0

	for c in get_children():
		c.queue_free()

	var margin := MarginContainer.new()
	margin.anchor_right = 1
	margin.anchor_bottom = 1
	margin.offset_left = 32
	margin.offset_top = 32
	margin.offset_right = -32
	margin.offset_bottom = -32
	add_child(margin)

	var panel := PanelContainer.new()
	panel.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	panel.size_flags_vertical = Control.SIZE_EXPAND_FILL
	margin.add_child(panel)

	var center := CenterContainer.new()
	center.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	center.size_flags_vertical = Control.SIZE_EXPAND_FILL
	panel.add_child(center)

	var card := PanelContainer.new()
	card.custom_minimum_size = Vector2(560, 0)
	center.add_child(card)

	var vbox := VBoxContainer.new()
	vbox.add_theme_constant_override("separation", 12)
	vbox.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	card.add_child(vbox)

	var title := Label.new()
	title.text = "Login / Register"
	title.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	title.add_theme_font_size_override("font_size", 40)
	title.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	vbox.add_child(title)

	var hint := Label.new()
	hint.text = "Login nav obligāts. Vari spēlēt kā 'guest', bet rezultāti DB būs piesaistīti kontam, ja ielogosies."
	hint.autowrap_mode = TextServer.AUTOWRAP_WORD
	hint.add_theme_font_size_override("font_size", 16)
	hint.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	vbox.add_child(hint)

	var u_label := Label.new()
	u_label.text = "Username"
	u_label.add_theme_font_size_override("font_size", 18)
	vbox.add_child(u_label)

	username_edit = LineEdit.new()
	username_edit.placeholder_text = "piem. player1"
	username_edit.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	vbox.add_child(username_edit)

	var p_label := Label.new()
	p_label.text = "Password"
	p_label.add_theme_font_size_override("font_size", 18)
	vbox.add_child(p_label)

	password_edit = LineEdit.new()
	password_edit.placeholder_text = "••••••••"
	password_edit.secret = true
	password_edit.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	vbox.add_child(password_edit)

	var row := HBoxContainer.new()
	row.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	row.add_theme_constant_override("separation", 12)
	vbox.add_child(row)

	btn_login = Button.new()
	btn_login.text = "Login"
	btn_login.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	btn_login.pressed.connect(_on_login_pressed)
	row.add_child(btn_login)

	btn_register = Button.new()
	btn_register.text = "Register"
	btn_register.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	btn_register.pressed.connect(_on_register_pressed)
	row.add_child(btn_register)

	status_label = Label.new()
	status_label.text = ""
	status_label.autowrap_mode = TextServer.AUTOWRAP_WORD
	status_label.add_theme_font_size_override("font_size", 16)
	status_label.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	vbox.add_child(status_label)

	var footer := HBoxContainer.new()
	footer.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	vbox.add_child(footer)
	footer.add_spacer(true)

	btn_back = Button.new()
	btn_back.text = "Back"
	btn_back.pressed.connect(_go_back)
	footer.add_child(btn_back)

	footer.add_spacer(true)

	# Enter uzvedība
	username_edit.text_submitted.connect(func(_t): password_edit.grab_focus())
	password_edit.text_submitted.connect(func(_t): _on_login_pressed())

	username_edit.grab_focus()

func _set_status(t: String) -> void:
	if status_label != null:
		status_label.text = t

func _go_back() -> void:
	var menu_path := "res://scenes/MainMenu.tscn"
	if ResourceLoader.exists(menu_path):
		get_tree().change_scene_to_file(menu_path)

func _validate_inputs() -> Dictionary:
	var u := username_edit.text.strip_edges()
	var p := password_edit.text.strip_edges()
	if u == "" or p == "":
		return {"ok": false, "error": "Ievadi username un password."}
	if u.length() > 32:
		return {"ok": false, "error": "Username par garu (max 32)."}
	if p.length() < 8:
		return {"ok": false, "error": "Password pa isu (min 8)."}
	if p.length() > 32:
		return {"ok": false, "error": "password pa garu (max 32)."}
	return {"ok": true, "u": u, "p": p}

func _on_register_pressed() -> void:
	if net == null:
		_set_status("NetAPI nav atrasts (/root/NetAPI).")
		return

	var v := _validate_inputs()
	if v.get("ok", false) != true:
		_set_status(str(v.get("error", "Invalid input")))
		return

	var u: String = v["u"]
	var p: String = v["p"]

	btn_login.disabled = true
	btn_register.disabled = true
	_set_status("Register...")

	var resp: Dictionary = await net.register_user(u, p)

	btn_login.disabled = false
	btn_register.disabled = false

	if resp.get("ok", false) == true:
		_set_status("Konts izveidots! Tagad spied Login.")
	else:
		_set_status("Register failed: %s" % str(resp.get("error", resp)))

func _on_login_pressed() -> void:
	if net == null:
		_set_status("NetAPI nav atrasts (/root/NetAPI).")
		return

	var v := _validate_inputs()
	if v.get("ok", false) != true:
		_set_status(str(v.get("error", "Invalid input")))
		return

	var u: String = v["u"]
	var p: String = v["p"]

	btn_login.disabled = true
	btn_register.disabled = true
	_set_status("Login...")

	var resp: Dictionary = await net.login_user(u, p)

	btn_login.disabled = false
	btn_register.disabled = false

	if resp.get("ok", false) == true:
		var uid: int = int(resp.get("user_id", 0))
		var uname: String = str(resp.get("username", u))

		if gm != null and gm.has_method("set_login"):
			gm.call("set_login", uname, uid)

		_set_status("Logged in: %s" % uname)
		await get_tree().create_timer(0.25).timeout
		_go_back()
	else:
		_set_status("Login failed: %s" % str(resp.get("error", resp)))
