#include "UICharacterCreatePage_Base.h"

#include "ZMMO.h"
#include "CharServerOpcodes.h"
#include "UIFrontEndFlowSubsystem.h"
#include "WireHelpers.h"
#include "ZeusCharServerSubsystem.h"
#include "Components/EditableTextBox.h"
#include "Components/ComboBoxString.h"
#include "CommonTextBlock.h"
#include "Engine/GameInstance.h"
#include "UI/Widgets/UIButton_Base.h"

using ZeusWire::WriteUuid16;
using ZeusWire::WriteUInt8;
using ZeusWire::WriteUInt16;
using ZeusWire::WriteUInt32;
using ZeusWire::WriteStringUtf8;

void UUICharacterCreatePage_Base::NativeConstruct()
{
	Super::NativeConstruct();
	if (!bBound)
	{
		if (Btn_Confirm) Btn_Confirm->OnClicked().AddUObject(this, &UUICharacterCreatePage_Base::HandleSubmitClicked);
		if (Btn_Cancel)  Btn_Cancel->OnClicked().AddUObject(this, &UUICharacterCreatePage_Base::HandleCancelClicked);
		bBound = true;
	}
	if (Text_Error) Text_Error->SetText(FText::GetEmpty());
}

void UUICharacterCreatePage_Base::NativeDestruct()
{
	if (bBound)
	{
		if (Btn_Confirm) Btn_Confirm->OnClicked().RemoveAll(this);
		if (Btn_Cancel)  Btn_Cancel->OnClicked().RemoveAll(this);
		bBound = false;
	}
	Super::NativeDestruct();
}

void UUICharacterCreatePage_Base::SubmitCreate()
{
	const FString Name = Input_Name ? Input_Name->GetText().ToString() : FString();
	if (Name.IsEmpty())
	{
		if (Text_Error) Text_Error->SetText(FText::FromString(TEXT("Informe um nome.")));
		return;
	}

	UGameInstance* GI = GetGameInstance();
	if (!GI) return;
	UUIFrontEndFlowSubsystem* Flow = GI->GetSubsystem<UUIFrontEndFlowSubsystem>();
	UZeusCharServerSubsystem* Char = GI->GetSubsystem<UZeusCharServerSubsystem>();
	if (!Flow || !Char) return;

	const FString RealmId = Flow->GetSelectedRealmId();
	if (RealmId.IsEmpty())
	{
		if (Text_Error) Text_Error->SetText(FText::FromString(TEXT("Realm nao selecionado.")));
		return;
	}

	int32 ClassId = 0;
	if (Combo_Class)
	{
		const FString Sel = Combo_Class->GetSelectedOption();
		LexFromString(ClassId, *Sel);
	}

	// Slot: simples, sempre 0 por enquanto (servidor valida unicidade na conta).
	const uint8 SlotIdx = 0;

	TArray<uint8> Payload;
	if (!WriteUuid16(Payload, RealmId))
	{
		if (Text_Error) Text_Error->SetText(FText::FromString(TEXT("RealmId invalido.")));
		return;
	}
	WriteUInt8(Payload, SlotIdx);
	WriteStringUtf8(Payload, Name);
	WriteUInt16(Payload, static_cast<uint16>(ClassId));
	WriteUInt32(Payload, 0); // hair
	WriteUInt32(Payload, 0); // hairColor
	WriteUInt32(Payload, 0); // skinColor
	WriteUInt8(Payload, 0);  // bodyType

	Char->SendCharRequest(ZeusCharOp::C_CHAR_CREATE, Payload);
	if (Text_Error) Text_Error->SetText(FText::GetEmpty());
	OnRequestSent.Broadcast();
}

void UUICharacterCreatePage_Base::CancelCreate()
{
	OnCancelled.Broadcast();
}
