#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 ZMMOWire::WriteUuid16;
using ZMMOWire::WriteUInt8;
using ZMMOWire::WriteUInt16;
using ZMMOWire::WriteUInt32;
using ZMMOWire::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 WorldId = Flow->GetSelectedWorldId();
	if (WorldId.IsEmpty())
	{
		if (Text_Error) Text_Error->SetText(FText::FromString(TEXT("Mundo 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, WorldId))
	{
		if (Text_Error) Text_Error->SetText(FText::FromString(TEXT("WorldId 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(ZMMOCharOp::C_CHAR_CREATE, Payload);
	if (Text_Error) Text_Error->SetText(FText::GetEmpty());
	OnRequestSent.Broadcast();
}

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