/**************************************************************************/
/*  export_dialog.cpp                                                     */
/**************************************************************************/
/*                         This file is part of:                          */
/*                          AETHEX ENGINE                                 */
/*                     https://aethex.foundation                          */
/**************************************************************************/
/* Copyright (c) 2026-present AeThex Labs.                                */
/**************************************************************************/

#ifdef TOOLS_ENABLED

#include "export_dialog.h"

#include "scene/gui/file_dialog.h"
#include "scene/gui/separator.h"
#include "core/os/time.h"
#include "editor/editor_node.h"
#include "editor/themes/editor_scale.h"

#include "../roblox_exporter.h"
#include "../uefn_exporter.h"
#include "../unity_exporter.h"
#include "../web_exporter.h"

void AeThexExportDialog::_bind_methods() {
	ADD_SIGNAL(MethodInfo("export_completed", PropertyInfo(Variant::INT, "result")));
}

AeThexExportDialog::AeThexExportDialog() {
	set_title("AeThex Cross-Platform Export");
	set_min_size(Size2(800, 600) * EDSCALE);
	
	current_config.instantiate();
	
	main_split = memnew(HSplitContainer);
	main_split->set_split_offset(200 * EDSCALE);
	add_child(main_split);
	
	// ==========================================
	// Left Panel - Platform List
	// ==========================================
	platform_panel = memnew(VBoxContainer);
	main_split->add_child(platform_panel);
	
	Label *platform_label = memnew(Label);
	platform_label->set_text("Export Targets");
	platform_panel->add_child(platform_label);
	
	platform_list = memnew(ItemList);
	platform_list->set_v_size_flags(Control::SIZE_EXPAND_FILL);
	platform_list->connect("item_selected", callable_mp(this, &AeThexExportDialog::_on_platform_selected));
	platform_panel->add_child(platform_list);
	
	HBoxContainer *preset_buttons = memnew(HBoxContainer);
	platform_panel->add_child(preset_buttons);
	
	add_preset_button = memnew(Button);
	add_preset_button->set_text("+");
	add_preset_button->set_tooltip_text("Add export preset");
	add_preset_button->connect("pressed", callable_mp(this, &AeThexExportDialog::_on_add_preset));
	preset_buttons->add_child(add_preset_button);
	
	remove_preset_button = memnew(Button);
	remove_preset_button->set_text("-");
	remove_preset_button->set_tooltip_text("Remove selected preset");
	remove_preset_button->connect("pressed", callable_mp(this, &AeThexExportDialog::_on_remove_preset));
	preset_buttons->add_child(remove_preset_button);
	
	// ==========================================
	// Right Panel - Settings
	// ==========================================
	VBoxContainer *right_panel = memnew(VBoxContainer);
	right_panel->set_h_size_flags(Control::SIZE_EXPAND_FILL);
	main_split->add_child(right_panel);
	
	settings_tabs = memnew(TabContainer);
	settings_tabs->set_v_size_flags(Control::SIZE_EXPAND_FILL);
	right_panel->add_child(settings_tabs);
	
	// General tab
	general_tab = memnew(VBoxContainer);
	general_tab->set_name("General");
	settings_tabs->add_child(general_tab);
	
	_add_setting_row(general_tab, "Project Name:", project_name_edit = memnew(LineEdit));
	_add_setting_row(general_tab, "Version:", version_edit = memnew(LineEdit));
	
	HBoxContainer *output_row = memnew(HBoxContainer);
	general_tab->add_child(output_row);
	
	Label *output_label = memnew(Label);
	output_label->set_text("Output Path:");
	output_label->set_custom_minimum_size(Size2(120, 0) * EDSCALE);
	output_row->add_child(output_label);
	
	output_path_edit = memnew(LineEdit);
	output_path_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
	output_row->add_child(output_path_edit);
	
	browse_output_button = memnew(Button);
	browse_output_button->set_text("Browse");
	browse_output_button->connect("pressed", callable_mp(this, &AeThexExportDialog::_on_browse_output));
	output_row->add_child(browse_output_button);
	
	// Platform tabs
	roblox_tab = memnew(VBoxContainer);
	roblox_tab->set_name("Roblox");
	settings_tabs->add_child(roblox_tab);
	_setup_roblox_settings(roblox_tab);
	
	uefn_tab = memnew(VBoxContainer);
	uefn_tab->set_name("UEFN");
	settings_tabs->add_child(uefn_tab);
	_setup_uefn_settings(uefn_tab);
	
	unity_tab = memnew(VBoxContainer);
	unity_tab->set_name("Unity");
	settings_tabs->add_child(unity_tab);
	_setup_unity_settings(unity_tab);
	
	web_tab = memnew(VBoxContainer);
	web_tab->set_name("Web");
	settings_tabs->add_child(web_tab);
	_setup_web_settings(web_tab);
	
	// Export controls
	right_panel->add_child(memnew(HSeparator));
	
	export_buttons = memnew(HBoxContainer);
	right_panel->add_child(export_buttons);
	
	export_button = memnew(Button);
	export_button->set_text("Export Selected");
	export_button->set_h_size_flags(Control::SIZE_EXPAND_FILL);
	export_button->connect("pressed", callable_mp(this, &AeThexExportDialog::_on_export_pressed));
	export_buttons->add_child(export_button);
	
	export_all_button = memnew(Button);
	export_all_button->set_text("Export All");
	export_all_button->connect("pressed", callable_mp(this, &AeThexExportDialog::_on_export_all_pressed));
	export_buttons->add_child(export_all_button);
	
	export_progress = memnew(ProgressBar);
	export_progress->set_visible(false);
	right_panel->add_child(export_progress);
	
	export_log = memnew(RichTextLabel);
	export_log->set_custom_minimum_size(Size2(0, 100) * EDSCALE);
	right_panel->add_child(export_log);
	
	_populate_platform_list();
}

AeThexExportDialog::~AeThexExportDialog() {
}

void AeThexExportDialog::_add_setting_row(VBoxContainer *p_parent, const String &p_label, Control *p_control) {
	HBoxContainer *row = memnew(HBoxContainer);
	p_parent->add_child(row);
	
	Label *label = memnew(Label);
	label->set_text(p_label);
	label->set_custom_minimum_size(Size2(120, 0) * EDSCALE);
	row->add_child(label);
	
	p_control->set_h_size_flags(Control::SIZE_EXPAND_FILL);
	row->add_child(p_control);
}

void AeThexExportDialog::_setup_roblox_settings(VBoxContainer *p_tab) {
	Label *info = memnew(Label);
	info->set_text("Roblox Export Settings");
	info->add_theme_font_size_override("font_size", 16 * EDSCALE);
	p_tab->add_child(info);
	
	LineEdit *game_id = memnew(LineEdit);
	game_id->set_placeholder("Game ID (optional)");
	_add_setting_row(p_tab, "Game ID:", game_id);
	
	CheckBox *auto_publish = memnew(CheckBox);
	auto_publish->set_text("Auto-publish to Roblox");
	p_tab->add_child(auto_publish);
	
	CheckBox *generate_rojo = memnew(CheckBox);
	generate_rojo->set_text("Generate Rojo project file");
	generate_rojo->set_pressed(true);
	p_tab->add_child(generate_rojo);
}

void AeThexExportDialog::_setup_uefn_settings(VBoxContainer *p_tab) {
	Label *info = memnew(Label);
	info->set_text("UEFN Export Settings");
	info->add_theme_font_size_override("font_size", 16 * EDSCALE);
	p_tab->add_child(info);
	
	LineEdit *island_name = memnew(LineEdit);
	island_name->set_placeholder("Island Name");
	_add_setting_row(p_tab, "Island Name:", island_name);
	
	LineEdit *verse_ns = memnew(LineEdit);
	verse_ns->set_placeholder("namespace");
	_add_setting_row(p_tab, "Verse Namespace:", verse_ns);
}

void AeThexExportDialog::_setup_unity_settings(VBoxContainer *p_tab) {
	Label *info = memnew(Label);
	info->set_text("Unity Export Settings");
	info->add_theme_font_size_override("font_size", 16 * EDSCALE);
	p_tab->add_child(info);
	
	OptionButton *target = memnew(OptionButton);
	target->add_item("Standalone");
	target->add_item("Android");
	target->add_item("iOS");
	target->add_item("WebGL");
	_add_setting_row(p_tab, "Target Platform:", target);
	
	OptionButton *backend = memnew(OptionButton);
	backend->add_item("IL2CPP");
	backend->add_item("Mono");
	_add_setting_row(p_tab, "Scripting Backend:", backend);
}

void AeThexExportDialog::_setup_web_settings(VBoxContainer *p_tab) {
	Label *info = memnew(Label);
	info->set_text("Web Export Settings");
	info->add_theme_font_size_override("font_size", 16 * EDSCALE);
	p_tab->add_child(info);
	
	CheckBox *typescript = memnew(CheckBox);
	typescript->set_text("Use TypeScript");
	p_tab->add_child(typescript);
	
	OptionButton *module_format = memnew(OptionButton);
	module_format->add_item("ES Modules");
	module_format->add_item("CommonJS");
	module_format->add_item("IIFE");
	_add_setting_row(p_tab, "Module Format:", module_format);
	
	CheckBox *generate_html = memnew(CheckBox);
	generate_html->set_text("Generate HTML template");
	generate_html->set_pressed(true);
	p_tab->add_child(generate_html);
}

void AeThexExportDialog::popup_export_dialog() {
	_populate_platform_list();
	export_log->clear();
	popup_centered();
}

void AeThexExportDialog::set_config(const Ref<AeThexExportConfig> &p_config) {
	current_config = p_config;
	if (current_config.is_valid()) {
		project_name_edit->set_text(current_config->get_project_name());
		version_edit->set_text(current_config->get_version());
		output_path_edit->set_text(current_config->get_output_directory());
	}
}

void AeThexExportDialog::_populate_platform_list() {
	platform_list->clear();
	platform_list->add_item("Roblox (Luau)");
	platform_list->add_item("UEFN (Verse)");
	platform_list->add_item("Unity (C#)");
	platform_list->add_item("Web (JavaScript)");
}

void AeThexExportDialog::_on_platform_selected(int p_index) {
	selected_platform = p_index;
	settings_tabs->set_current_tab(p_index + 1);  // +1 for General tab
}

void AeThexExportDialog::_on_add_preset() {
	// Add new export preset
}

void AeThexExportDialog::_on_remove_preset() {
	// Remove selected preset
}

void AeThexExportDialog::_on_browse_output() {
	FileDialog *dialog = memnew(FileDialog);
	dialog->set_file_mode(FileDialog::FILE_MODE_OPEN_DIR);
	dialog->set_title("Select Output Directory");
	dialog->connect("dir_selected", callable_mp(this, &AeThexExportDialog::_on_output_selected));
	add_child(dialog);
	dialog->popup_centered_ratio(0.6);
}

void AeThexExportDialog::_on_output_selected(const String &p_path) {
	output_path_edit->set_text(p_path);
}

void AeThexExportDialog::_on_export_pressed() {
	if (selected_platform >= 0 && selected_platform < AeThexExportConfig::PLATFORM_COUNT) {
		_save_current_settings();
		_export_to_platform((AeThexExportConfig::Platform)selected_platform);
	}
}

void AeThexExportDialog::_on_export_all_pressed() {
	_save_current_settings();
	
	_log_message("Exporting to all platforms...");
	
	for (int i = 0; i < AeThexExportConfig::PLATFORM_COUNT; i++) {
		_export_to_platform((AeThexExportConfig::Platform)i);
	}
	
	_log_message("All exports completed!");
}

void AeThexExportDialog::_save_current_settings() {
	if (current_config.is_valid()) {
		current_config->set_project_name(project_name_edit->get_text());
		current_config->set_version(version_edit->get_text());
		current_config->set_output_directory(output_path_edit->get_text());
	}
}

void AeThexExportDialog::_export_to_platform(AeThexExportConfig::Platform p_platform) {
	Ref<AeThexPlatformExporter> exporter;
	
	switch (p_platform) {
		case AeThexExportConfig::PLATFORM_ROBLOX:
			exporter = Ref<AeThexRobloxExporter>(memnew(AeThexRobloxExporter));
			break;
		case AeThexExportConfig::PLATFORM_UEFN:
			exporter = Ref<AeThexUEFNExporter>(memnew(AeThexUEFNExporter));
			break;
		case AeThexExportConfig::PLATFORM_UNITY:
			exporter = Ref<AeThexUnityExporter>(memnew(AeThexUnityExporter));
			break;
		case AeThexExportConfig::PLATFORM_WEB:
			exporter = Ref<AeThexWebExporter>(memnew(AeThexWebExporter));
			break;
		default:
			return;
	}
	
	exporter->set_config(current_config);
	
	String output_path = output_path_edit->get_text();
	String platform_name = AeThexExportConfig::get_platform_name(p_platform);
	
	_log_message("Starting export to " + platform_name + "...");
	
	export_progress->set_visible(true);
	export_progress->set_value(0);
	is_exporting = true;
	
	AeThexPlatformExporter::ExportResult result = exporter->export_project(
		output_path.path_join(platform_name.to_lower())
	);
	
	export_progress->set_value(100);
	is_exporting = false;
	
	_on_export_completed(result);
	
	// Show errors
	for (const String &err : exporter->get_errors()) {
		_log_message("ERROR: " + err);
	}
	for (const String &warn : exporter->get_warnings()) {
		_log_message("WARNING: " + warn);
	}
	
	export_progress->set_visible(false);
}

void AeThexExportDialog::_on_export_completed(AeThexPlatformExporter::ExportResult p_result) {
	String platform_name = selected_platform >= 0 ? 
		AeThexExportConfig::get_platform_name((AeThexExportConfig::Platform)selected_platform) : "Unknown";
	
	switch (p_result) {
		case AeThexPlatformExporter::RESULT_SUCCESS:
			_log_message("Export to " + platform_name + " completed successfully!");
			break;
		case AeThexPlatformExporter::RESULT_ERROR_INVALID_CONFIG:
			_log_message("Export failed: Invalid configuration");
			break;
		case AeThexPlatformExporter::RESULT_ERROR_COMPILE_FAILED:
			_log_message("Export failed: Compilation errors");
			break;
		case AeThexPlatformExporter::RESULT_ERROR_WRITE_FAILED:
			_log_message("Export failed: Could not write output files");
			break;
		default:
			_log_message("Export failed: Unknown error");
			break;
	}
	
	emit_signal("export_completed", (int)p_result);
}

void AeThexExportDialog::_log_message(const String &p_msg) {
	export_log->add_text("[" + Time::get_singleton()->get_time_string_from_system() + "] " + p_msg + "\n");
}

// ==========================================
// Export Plugin
// ==========================================

AeThexExportPlugin::AeThexExportPlugin() {
	export_dialog = memnew(AeThexExportDialog);
	EditorNode::get_singleton()->get_gui_base()->add_child(export_dialog);
	
	export_button = memnew(Button);
	export_button->set_text("AeThex Export");
	export_button->set_tooltip_text("Export to multiple platforms");
	export_button->connect("pressed", callable_mp(this, &AeThexExportPlugin::_on_export_pressed));
	add_control_to_container(CONTAINER_TOOLBAR, export_button);
}

AeThexExportPlugin::~AeThexExportPlugin() {
	remove_control_from_container(CONTAINER_TOOLBAR, export_button);
	memdelete(export_button);
	memdelete(export_dialog);
}

void AeThexExportPlugin::_on_export_pressed() {
	export_dialog->popup_export_dialog();
}

#endif // TOOLS_ENABLED
