/*
 * Mirai. Copyright (C) 2024 Vyn
 * This file is licensed under version 3 of the GNU General Public License (GPL-3.0-only)
 * The license can be found in the LICENSE file or at https://www.gnu.org/licenses/gpl-3.0.txt
 */

#include "AppWindow.h"
#include "../../SeleniteSetup.h"
#include "../../shared/Utils.h"
#include "mirai-core/DateTime.h"
#include "mirai-core/Day.h"
#include "mirai-core/MarkdownDataProvider.h"
#include "mirai-core/Mirai.h"
#include "selenite/palette.h"
#include "slint.h"
#include "slint_string.h"
#include "ui.h"
#include <bits/chrono.h>
#include <cassert>
#include <charconv>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <memory>
#include <optional>
#include <ostream>
#include <print>
#include <ranges>
#include <string>
#include <string_view>
#include <vector>

AppWindow::AppWindow(mirai::Mirai *miraiInstance)
	: miraiInstance_(miraiInstance), addSourceWindow_(miraiInstance),
	  editSourceWindow_(miraiInstance), settingsWindow_(miraiInstance),
	  editEventWindow_(miraiInstance), view_(miraiInstance)
{
	sources_ = std::make_shared<slint::VectorModel<ui::Source>>();
	days_ = std::make_shared<slint::VectorModel<ui::Day>>();
	calendar_ = std::make_shared<slint::VectorModel<ui::CalendarDay>>();
	unscheduledTasks_ = std::make_shared<slint::VectorModel<ui::TaskData>>();
	auto sourcesNames = std::make_shared<slint::MapModel<ui::Source, slint::SharedString>>(
		sources_, [&](const ui::Source &a) {
			return a.name;
		}
	);

	const auto palettePath = std::string(getenv("HOME")) + "/.config/evalyte/theme.json";
	const auto palette = selenite::parseJson(palettePath);
	if (palette.has_value()) {
		std::println(std::cerr, "Warning, no {} found", palettePath);
		setSelenitePalette(mainWindow_->global<ui::Palette>(), palette.value());
	}

	bindSlintUtils(mainWindow_->global<ui::Utils>());

	models().set_sources(sourcesNames);
	models().set_sources_selected(sources_);
	models().set_days(days_);
	models().set_calendar(calendar_);

	view_.setAllSources();
	view_.update();

	reloadSources();
	reloadTasks();

	setupCallbacks();
}

std::optional<ui::Date> stringToDate(const std::string &dateStr)
{
	using std::operator""sv;

	auto dateSplitView =
		dateStr | std::views::split("-"sv) | std::views::transform([](auto v) -> int {
			int i = 0;
			std::from_chars(v.data(), v.data() + v.size(), i);
			return i;
		});
	std::vector<int> dateSplit{dateSplitView.begin(), dateSplitView.end()};
	if (dateSplit.size() != 3) {
		return std::nullopt;
	}

	auto year = dateSplit[0];
	auto month = dateSplit[1];
	auto day = dateSplit[2];
	return ui::Date{.year = year, .month = month, .day = day};
}

void AppWindow::setupCallbacks()
{
	models().on_get_source_id_from_name([&](slint::SharedString name) {
		auto source = miraiInstance_->getSourceByName(std::string(name));
		assert(source);
		return source->id;
	});

	models().on_get_source_name_from_id([&](int sourceId) {
		auto source = miraiInstance_->getSourceById(sourceId);
		assert(source);
		return slint::SharedString(source->name());
	});

	miraiInstance_->onSourceAdded([&](mirai::Source *source) {
		refreshModels();
	});
	miraiInstance_->onSourceEdited([&](mirai::Source *source) {
		refreshModels();
	});
	miraiInstance_->onSourceDeleted([&](int id) {
		refreshModels();
	});
	actions().on_open_settings_window([&]() {
		settingsWindow_.open();
	});
	actions().on_open_add_source_window([&]() {
		addSourceWindow_.open();
	});
	actions().on_open_edit_source_window([&](int sourceId) {
		auto source = miraiInstance_->getSourceById(sourceId);
		assert(source);
		editSourceWindow_.open(source);
	});
	actions().on_open_add_event_window([&]() {
		editEventWindow_.open();
	});

	actions().on_task_clicked([&](int sourceId, int taskId) {
		auto source = miraiInstance_->getSourceById(sourceId);
		assert(source);
		auto task = source->getTaskById(taskId);
		assert(task);
		if (!task->checked() && !task->hasDate() && !task->hasEvent()) {
			task->setDate(mirai::Date(mirai::Date(std::chrono::system_clock::now())));
		}
		task->setChecked(!task->checked());
		miraiInstance_->save();
		view_.update();
		reloadTasks();
	});

	actions().on_source_clicked([&](int index) {
		// index with value -1 is equal to no selection, aka "All"
		if (index == -1) {
			view_.setAllSources();
		} else {
			view_.removeSources();
			const mirai::Source *source = miraiInstance_->getSourceById(index);
			view_.addSource(*source);
		}
		models().set_default_source_index(index == -1 ? 0 : index);
		view_.update();
		reloadSources();
		reloadTasks();
	});

	actions().on_delete_task_clicked([&](int sourceId, int taskId) {
		auto source = miraiInstance_->getSourceById(sourceId);
		assert(source);
		auto task = source->getTaskById(taskId);
		assert(task);
		source->removeTask(*task);
		miraiInstance_->save();
		view_.update();
		reloadTasks();
	});

	actions().on_toggle_show_completed_tasks([&] {
		view_.hideCompletedTasks(!view_.shouldHideCompletedTasks());
		view_.update();
		reloadTasks();
	});

	actions().on_save_task([&](ui::SaveTaskData newTaskData) {
		auto source = miraiInstance_->getSourceById(newTaskData.sourceId);
		assert(source);
		auto task = source->getTaskById(newTaskData.id);
		assert(task.has_value());
		const mirai::Date &date = SlintDateToMiraiDate(newTaskData.date);
		const auto dayOpt = source->getDayByDate(date);
		task->setTitle(std::string(newTaskData.title));

		if (!task.value().hasEvent() && date.year != 0) {
			task->setDate(date);
		}

		if (!task.value().hasEvent() && date.year == 0) {
			task->unschedule();
		}

		miraiInstance_->save();
		view_.update();
		reloadTasks();
	});

	actions().on_create_task([&](ui::NewTaskData newTaskData) {
		std::optional<mirai::Date> date = std::nullopt;
		if (newTaskData.date.year != 0) {
			date = SlintDateToMiraiDate(newTaskData.date);
		}
		auto source = miraiInstance_->getSourceById(newTaskData.sourceId);

		std::optional<mirai::Event> event = std::nullopt;
		if (newTaskData.eventId >= 0) {
			event = source->getEventById(newTaskData.eventId);
		}

		source->createTask({
			.title = std::string(newTaskData.title),
			.event = event,
			.date = date,
		});

		miraiInstance_->save();
		view_.update();
		reloadTasks();
	});

	actions().on_delete_event([&](int sourceId, int eventId) {
		auto source = miraiInstance_->getSourceById(sourceId);
		assert(source);
		auto event = source->getEventById(eventId);
		assert(event.has_value());
		source->removeEvent(event.value());
		miraiInstance_->save();
		view_.update();
		reloadTasks();
	});

	actions().on_create_event([&](ui::CreateEventParams newEventParams) {
		std::println("okkk");
		const ui::Date &date = newEventParams.date;
		const std::string dateStr = SlintDateToStdString(date);
		const auto sourceId = models().get_default_source_index();
		auto source = miraiInstance_->getSourceById(sourceId == -1 ? 0 : sourceId);

		source->createEvent({
			.title = std::string(newEventParams.title),
			.date = SlintDateToMiraiDate(newEventParams.date),
			.startsAt = SlintTimeToMiraiTime(newEventParams.startsAt),
			.endsAt = SlintTimeToMiraiTime(newEventParams.endsAt),
		});
		miraiInstance_->save();
		view_.update();
		reloadTasks();
	});

	/*actions().on_save_event([&](ui::SaveEventParams newEventParams) {*/
	/*const ui::Date &date = newEventParams.date;*/
	/*const std::string dateStr = SlintDateToStdString(date);*/
	/*auto source = miraiInstance_->getSourceById(newEventParams.sourceId);*/
	/*assert(source);*/
	/*auto event = source->getEventById(newEventParams.id);*/
	/*assert(event);*/
	/*event->setTitle(std::string(newEventParams.title));*/
	/*event->setStartTime(SlintTimeToMiraiTime(newEventParams.startsAt));*/
	/*event->setEndTime(SlintTimeToMiraiTime(newEventParams.endsAt));*/

	/*// TODO we can't change the date of the event for now.*/

	/*miraiInstance_->save();*/
	/*view_.update();*/
	/*reloadTasks();*/
	/*});*/
}

std::shared_ptr<slint::VectorModel<slint::SharedString>>
stdToSlintStringVector(const std::vector<std::string> &stdVector)
{
	auto slintVector = std::make_shared<slint::VectorModel<slint::SharedString>>();
	for (const auto &item : stdVector) {
		slintVector->push_back(slint::SharedString(item));
	}
	return slintVector;
}

void AppWindow::reloadTasks()
{
	days_->clear();
	if (miraiInstance_->getSources().size() == 0) {
		return;
	}
	auto todayDate = mirai::Date(std::chrono::system_clock::now());
	auto dates = view_.getDates();
	auto slintDays = std::make_shared<slint::VectorModel<ui::Day>>();
	for (int dayIndex = 0; dayIndex < dates.size(); ++dayIndex) {
		auto &currentDate = dates.at(dayIndex);
		auto slintEvents = std::make_shared<slint::VectorModel<ui::Event>>();
		auto slintDayTasks = std::make_shared<slint::VectorModel<ui::TaskData>>();
		auto relativeDaysDiff = std::chrono::duration_cast<std::chrono::days>(
									std::chrono::sys_days(currentDate.toStdChrono()) -
									std::chrono::sys_days(todayDate.toStdChrono())
		)
									.count();
		slintDays->push_back(
			ui::Day{
				.date = MiraiDateToSlintDate(currentDate),
				.events = slintEvents,
				.tasks = slintDayTasks,
				.isLate = currentDate < todayDate,
				.isToday = currentDate == todayDate,
				.relativeDaysDiff = static_cast<int>(relativeDaysDiff)
			}
		);
		// Day's tasks
		const std::vector<mirai::Task> tasksForDate = view_.getTasksForDate(currentDate);
		for (int taskIndex = 0; taskIndex < tasksForDate.size(); ++taskIndex) {
			auto &task = tasksForDate.at(taskIndex);
			slintDayTasks->push_back({
				.sourceId = task.sourceId(),
				.eventId = -1,
				.id = task.id(),
				.title = slint::SharedString(task.title()),
				.checked = task.checked(),
			});
		}

		// Day's events
		const std::vector<mirai::Event> eventsForDate = view_.getEventsForDate(currentDate);
		for (int eventIndex = 0; eventIndex < eventsForDate.size(); ++eventIndex) {
			auto &currentEvent = eventsForDate.at(eventIndex);
			auto slintTasks = std::make_shared<slint::VectorModel<ui::TaskData>>();
			slintEvents->push_back(
				ui::Event{
					.sourceId = currentEvent.sourceId(),
					.id = currentEvent.id(),
					.title = slint::SharedString(currentEvent.title()),
					.startsAt = MiraiTimeToSlintTime(currentEvent.startsAt()),
					.endsAt = MiraiTimeToSlintTime(currentEvent.endsAt()),
					.tasks = slintTasks,
				}
			);
			auto eventTasks = currentEvent.queryTasks();
			for (int taskIndex = 0; taskIndex < eventTasks.size(); ++taskIndex) {
				auto &task = eventTasks.at(taskIndex);
				slintTasks->push_back({
					.sourceId = task.sourceId(),
					.eventId = currentEvent.id(),
					.id = task.id(),
					.title = slint::SharedString(task.title()),
					.checked = task.checked(),
				});
			}
		}
	}
	days_ = slintDays;
	models().set_days(days_);

	auto unscheduledTasksView = view_.getUnscheduledTasks();
	unscheduledTasks_->clear();
	for (int taskIndex = 0; taskIndex < unscheduledTasksView.size(); ++taskIndex) {
		auto &task = unscheduledTasksView.at(taskIndex);
		const auto &source = miraiInstance_->getSourceById(task.sourceId());
		std::println("request name for source id {} : {}", task.sourceId(), source->name());
		unscheduledTasks_->push_back({
			.sourceId = task.sourceId(),
			.eventId = -1,
			.id = task.id(),
			.title = slint::SharedString(task.title()),
			.checked = task.checked(),
		});
	}
	models().set_unscheduled_tasks(unscheduledTasks_);

	calendar_->clear();
	for (int dayIndex = 0; dayIndex < 7; ++dayIndex) {
		std::chrono::year_month_day nextDate =
			std::chrono::floor<std::chrono::days>(std::chrono::system_clock::now()) +
			std::chrono::days{dayIndex};
		auto currentDate = mirai::Date{nextDate};
		auto events = view_.getEventsForDate(currentDate);
		auto slintEvents = std::make_shared<slint::VectorModel<ui::CalendarDayEvent>>();
		auto relativeDaysDiff = std::chrono::duration_cast<std::chrono::days>(
									std::chrono::sys_days(currentDate.toStdChrono()) -
									std::chrono::sys_days(todayDate.toStdChrono())
		)
									.count();
		if (relativeDaysDiff < 0 || relativeDaysDiff >= 7) {
			continue;
		}
		const std::vector<mirai::Event> eventsForDate = view_.getEventsForDate(currentDate);
		for (int eventIndex = 0; eventIndex < eventsForDate.size(); ++eventIndex) {
			auto &currentEvent = eventsForDate.at(eventIndex);
			slintEvents->push_back(
				ui::CalendarDayEvent{
					.sourceId = currentEvent.sourceId(),
					.id = currentEvent.id(),
					.title = slint::SharedString(currentEvent.title()),
					.startsAt = MiraiTimeToSlintTime(currentEvent.startsAt()),
					.endsAt = MiraiTimeToSlintTime(currentEvent.endsAt()),
				}
			);
		}

		auto calendarDay = ui::CalendarDay{
			.events = slintEvents,
			.date = MiraiDateToSlintDate(currentDate),
			.header = slint::SharedString(
				capitalize(formatDateRelative(MiraiDateToSlintDate(currentDate)))
			)
		};
		calendar_->push_back(calendarDay);
	}
}

void AppWindow::reloadSources()
{
	sources_->clear();
	bool noSourceSelected = miraiInstance_->getSources().size() == view_.activeSourceCount();
	for (const auto &source : miraiInstance_->getSources()) {
		bool isSourceSelected = view_.isSourceSelected(*source);
		mirai::MarkdownDataProvider *sourceProvider =
			dynamic_cast<mirai::MarkdownDataProvider *>(source->dataProvider());
		sources_->push_back(
			{.id = source->id,
			 .name = slint::SharedString(source->name()),
			 .selected = isSourceSelected && !noSourceSelected,
			 .path = slint::SharedString(sourceProvider->path())}
		);
	}
	models().set_no_source_selected(noSourceSelected);
}

void AppWindow::refreshModels()
{
	view_.setAllSources();
	view_.update();
	reloadSources();
	reloadTasks();
}

void AppWindow::run()
{
	mainWindow_->run();
}

const ui::AppWindowModels &AppWindow::models()
{
	return mainWindow_->global<ui::AppWindowModels>();
}

const ui::AppWindowActions &AppWindow::actions()
{
	return mainWindow_->global<ui::AppWindowActions>();
}
