// File: ./src/gui/message.rs
// SPDX-License-Identifier: GPL-3.0-or-later
/*
File: cfait/src/gui/message.rs
Defines all messages used for the Elm architecture in the GUI.
*/

use crate::client::RustyClient;
use crate::config::{AppTheme, Config, LogLevel};
use crate::gui::state::{ResizeDirection, SidebarMode};
use crate::model::{CalendarListEntry, Task as TodoTask};
use crate::system::{AlarmMessage, SystemEvent};
use iced::widget::text_editor;
use std::sync::Arc;
use tokio::sync::mpsc;

pub type LoadedResult = Result<
    (
        RustyClient,
        Vec<CalendarListEntry>,
        Vec<TodoTask>,
        Option<String>,
        Option<String>,
    ),
    String,
>;

#[derive(Debug, Clone)]
pub enum Message {
    // --- Settings & Onboarding ---
    ObUrlChanged(String),
    ObUserChanged(String),
    ObPassChanged(String),
    ToggleObPasswordVisibility,
    ObInsecureToggled(bool),
    ToggleCalendarVisibility(String, bool),
    ToggleCalendarDisabled(String, bool),
    ObDefaultCalChanged(String),
    ObSubmit,
    OpenSettings,
    CancelSettings,
    ObSubmitOffline,

    // --- Input & Editing ---
    InputChanged(text_editor::Action),
    StartCreateWithDescription,
    DescriptionChanged(text_editor::Action),
    SearchChanged(text_editor::Action),
    ApplySearch(usize),
    ClearSearch,
    SubmitTask,
    ToggleTask(usize, bool),
    ToggleTaskShift(String),
    ToggleTaskShiftSelected,
    DeleteTask(usize),
    EditTaskStart(usize),
    CancelEdit,
    ChangePriority(usize, i8),
    SetTaskStatus(usize, crate::model::TaskStatus),
    StartTask(String),
    PauseTask(String),
    StopTask(String),

    // --- Keyboard Shortcuts (Stateless / Context-Aware) ---
    SelectNext,
    SelectPrev,
    SelectNextPage,
    SelectPrevPage,
    ArrowRight,
    ArrowLeft,
    SidebarInteractSpace,
    SidebarInteractEnter,
    DeleteSelected,
    ToggleSelected,
    EditSelected,
    EditSelectedDescription,
    PromoteSelected,
    DemoteSelected,
    YankSelected,
    ClearYank,
    EscapePressed,
    EscCaptured,
    KeyboardLinkChild,
    KeyboardCreateChild,
    StartAddSession(String),
    SessionInputChanged(iced::widget::text_editor::Action),
    SubmitSession,
    CancelAddSession,
    DeleteSession(String, usize),
    ToggleShowAllSessions(String),
    KeyboardAddSession,
    KeyboardToggleSessions,
    ClearAllFilters,
    KeyboardAddDependency,
    KeyboardAddRelation,
    KeyboardToggleTreeCollapse,
    KeyboardDuplicateTask,
    KeyboardDeleteTaskTree,
    KeyboardOpenLocations,
    KeyboardOpenUrl,
    KeyboardOpenContextMenu,
    KeyboardToggleDetails,
    EnterPressed,
    DuplicateTask(String),
    DeleteTaskTree(String),
    ToggleActiveSelected,
    StopSelected,
    CancelSelected,
    ChangePrioritySelected(i8),
    ToggleHideCompletedToggle,
    CategoryMatchModeToggle,
    ToggleSortStandardByPriorityToggle,
    FocusInput,
    FocusSearch,
    Refresh,

    ZoomIn,
    ZoomOut,
    ZoomReset,
    ToggleQuickFilter,
    ToggleSidebar,

    // --- View & Filter ---
    ToggleChildLock,
    ToggleYankLock,
    SetMinDuration(Option<u32>),
    SetMaxDuration(Option<u32>),
    ToggleIncludeUnsetDuration(bool),
    ToggleDetails(String),
    SidebarModeChanged(SidebarMode),
    SelectCalendar(String),
    IsolateCalendar(String),
    CategoryToggled(String),
    LocationToggled(String),
    ClearAllTags,
    ClearAllLocations,
    CategoryMatchModeChanged(bool),
    ToggleHideCompleted(bool),
    ToggleHideFullyCompletedTags(bool),
    ToggleHideAliasesInSidebar(bool),
    ToggleSortStandardByPriority(bool),
    SetSortPreset(crate::config::SortPreset),
    CycleFocus(bool),
    OpenHelp(crate::help::HelpTab),
    CloseHelp,
    SwitchHelpTab(bool),
    ToggleDoneGroup(String),
    ToggleTreeCollapse(String),
    ToggleTagCollapse(String),
    ToggleLocationCollapse(String),
    ToggleHelpSection(String),

    // --- Navigation & Actions ---
    ExtractSubtasks(String),
    TogglePin(String),
    YankTask(String),
    StartCreateChild(String),
    AddDependency(String),
    AddRelatedTo(String),
    MakeChild(String),
    RemoveParent(String),
    RemoveDependency(String, String),
    RemoveRelatedTo(String, String),
    AliasKeyInput(String),
    AliasValueInput(String),
    AddAlias,
    EditAlias(String, String),
    CancelEditAlias,
    RemoveAlias(String),
    StartMoveTask(String),
    CancelMoveTask,
    MoveTask(String, String),
    MoveSelected,
    MigrateLocalTo(String, String),
    JumpToTag(String),
    JumpToLocation(String),
    JumpToTask(String),
    JumpToRandomTask,
    SnapToSelected { focus: bool },
    TagHovered(Option<String>),
    FocusTag(String),
    FocusLocation(String),
    OpenUrl(String),
    OpenCoordinates(String),
    OpenLocations(String),
    TaskClick(usize, String),

    // --- System & Network Events ---
    ConfigLoaded(Result<Box<Config>, String>),
    ObSortMonthsChanged(String),
    ThemeChanged(AppTheme),
    Loaded(LoadedResult),
    TasksRefreshed(Result<(String, Vec<TodoTask>), String>),
    RefreshedAll(Result<Vec<(String, Vec<TodoTask>)>, String>),
    MigrationComplete(Result<usize, String>),
    FontLoaded(Result<(), String>),
    DismissError,
    ToggleAllCalendars(bool),
    Tick,
    InitBackgroundWorker(mpsc::Sender<crate::gui::async_ops::WorkerCommand>),
    BackgroundSyncComplete(Vec<TodoTask>),
    BackgroundSyncFailed,
    JournalSaved,

    // --- Window Management ---
    WindowDragged,
    MinimizeWindow,
    CloseWindow,
    WindowResized(iced::Size),
    ResizeStart(ResizeDirection),

    // --- Settings Input Fields ---
    ObUrgentDaysChanged(String),
    ObUrgentPrioChanged(String),
    ObDefaultPriorityChanged(String),
    ObStartGraceChanged(String),
    SetTrashRetention(String),
    SetLanguage(String),

    // --- Alarms & Reminders ---
    InitAlarmActor(mpsc::Sender<SystemEvent>),
    AlarmSignalReceived(Arc<AlarmMessage>),
    CompleteTaskFromAlarm(String, String),
    CancelTaskFromAlarm(String, String),
    SnoozeAlarm(String, String, u32),
    DismissAlarm(String, String),
    SnoozeCustomInput(String),
    SnoozeCustomSubmit(String, String),
    SetAutoReminders(bool),
    SetDefaultReminderTime(String),
    SetSnoozeShort(String),
    SetSnoozeLong(String),
    SetAutoRefreshInterval(String),

    SetShowQuickFilter(bool),
    SetQuickFilterTerm(String),
    SetQuickFilterIcon(String),

    // --- Context Menu ---
    OpenContextMenu(String, bool),
    CloseContextMenu,
    TogglePinnedAction(crate::config::TaskAction, bool),
    SetLogLevel(LogLevel),
    SetSyncSettings(bool),

    // --- Advanced Settings ---
    ToggleAdvancedSettings(bool),
    SetMaxDoneRoots(String),
    SetMaxDoneSubtasks(String),
    SetShowPriorityNumbers(bool),

    SetCreateEventsForTasks(bool),
    SetDeleteEventsOnCompletion(bool),
    SetStrikethroughCompleted(bool),
    DeleteAllCalendarEvents,
    BackfillEventsComplete(Result<usize, String>),

    // --- Local Calendar & ICS ---
    ExportLocalIcs(String),
    ExportSaved(Result<std::path::PathBuf, String>),
    ImportLocalIcs(String),
    ImportCompleted(Result<String, String>),
    IcsFileLoaded(Result<(String, String), String>),
    IcsImportDialogCalendarSelected(String),
    IcsImportDialogCancel,
    IcsImportDialogConfirm,
    AddLocalCalendar,
    DeleteLocalCalendar(String),
    LocalCalendarNameChanged(String, String),
    AddRemoteCalendar,
    RemoteCalendarNameChanged(String, String),
    SubmitRemoteCalendar(String),
    RemoteCalendarUpdated(String, Result<(), String>),
    RemoteCalendarCreated(String, Result<String, String>),
    OpenColorPicker(String, iced::Color),
    CancelColorPicker,
    SubmitColorPicker(iced::Color),
}
