ratado 0.2.0

A fast, keyboard-driven terminal task manager built with Rust and Ratatui
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
//! Command pattern implementation for decoupling input from actions.
//!
//! This module defines all possible commands that can be executed in the application.
//! Commands encapsulate actions and can be mapped from keyboard input, allowing for
//! flexible keybinding configuration and testable action handling.
//!
//! ## Architecture
//!
//! The command pattern provides several benefits:
//! - Decouples input handling from action execution
//! - Makes keybindings configurable
//! - Enables undo/redo functionality (future)
//! - Simplifies testing of individual actions
//!
//! ## Example
//!
//! ```rust,no_run
//! use ratado::handlers::commands::Command;
//! use ratado::app::App;
//!
//! # async fn example(app: &mut App) -> Result<(), Box<dyn std::error::Error>> {
//! // Execute a navigation command
//! let should_continue = Command::NavigateDown.execute(app).await?;
//!
//! // Execute a quit command
//! let should_continue = Command::Quit.execute(app).await?;
//! assert!(!should_continue); // Quit returns false to stop the loop
//! # Ok(())
//! # }
//! ```

use log::debug;
use tui_logger::TuiWidgetEvent;

use crate::app::{App, AppError, FocusPanel, InputMode, View};
use crate::models::{Filter, Priority, Task};
use crate::ui::dialogs::{AddTaskDialog, ConfirmDialog, DeleteProjectDialog, Dialog, FilterSortDialog, MoveToProjectDialog, ProjectDialog, QuickCaptureDialog, SettingsDialog};
use crate::ui::search::search_tasks;

/// All possible commands that can be executed in the application.
///
/// Commands are the actions that the application can perform in response
/// to user input. Each command encapsulates a specific action and knows
/// how to modify the application state.
#[derive(Debug, Clone, PartialEq)]
pub enum Command {
    // === Navigation ===
    /// Move selection up in the current list
    NavigateUp,
    /// Move selection down in the current list
    NavigateDown,
    /// Jump to the top of the current list
    NavigateTop,
    /// Jump to the bottom of the current list
    NavigateBottom,
    /// Scroll down by a page
    PageDown,
    /// Scroll up by a page
    PageUp,
    /// Switch focus between panels (sidebar/task list)
    SwitchPanel,
    /// Focus the sidebar panel
    FocusSidebar,
    /// Focus the task list panel
    FocusTaskList,

    // === Task Actions ===
    /// Start adding a new task
    AddTask,
    /// Open Quick Capture spotlight dialog
    QuickCapture,
    /// Edit the selected task
    EditTask,
    /// Delete the selected task
    DeleteTask,
    /// Toggle completion status of the selected task
    ToggleTaskStatus,
    /// Cycle through priority levels for the selected task
    CyclePriority,
    /// Move selected task to a different project
    MoveToProject,
    /// Edit tags on the selected task
    EditTags,
    /// Create a new project
    AddProject,
    /// Edit the selected project
    EditProject,
    /// Delete the selected project
    DeleteProject,

    // === Views ===
    /// Show the main task list view
    ShowMain,
    /// Show the help screen
    ShowHelp,
    /// Show the calendar view
    ShowCalendar,
    /// Enter search mode
    ShowSearch,
    /// Navigate up in search results
    SearchNavigateUp,
    /// Navigate down in search results
    SearchNavigateDown,
    /// Select the current search result
    SearchSelectTask,
    /// Toggle the debug logs view
    ShowDebugLogs,
    /// Show detailed view of selected task
    ShowTaskDetail,

    // === Calendar Navigation ===
    /// Move to previous day in calendar
    CalendarPrevDay,
    /// Move to next day in calendar
    CalendarNextDay,
    /// Move to previous week in calendar
    CalendarPrevWeek,
    /// Move to next week in calendar
    CalendarNextWeek,
    /// Jump to today in calendar
    CalendarToday,
    /// Select tasks for the current calendar day
    CalendarSelectDay,
    /// Toggle focus between day grid and task list
    CalendarToggleFocus,
    /// Move to previous task in calendar task list
    CalendarTaskUp,
    /// Move to next task in calendar task list
    CalendarTaskDown,
    /// Toggle selected task status in calendar
    CalendarToggleTask,
    /// Cycle priority of selected task in calendar
    CalendarCyclePriority,
    /// Edit selected task in calendar
    CalendarEditTask,
    /// Navigate to selected task in its project
    CalendarGoToTask,
    /// Toggle showing completed tasks in calendar
    CalendarToggleCompleted,

    // === Settings ===
    /// Show the settings dialog
    ShowSettings,

    // === Filters ===
    /// Set a specific filter
    SetFilter(Filter),
    /// Filter to show only tasks due today
    FilterToday,
    /// Filter to show only tasks due this week
    FilterThisWeek,
    /// Filter by priority level
    FilterByPriority(Priority),
    /// Open the filter/sort selection dialog
    ShowFilterSort,

    // === Input Mode ===
    /// Enter editing mode for text input
    EnterEditMode,
    /// Exit editing mode back to normal
    ExitEditMode,
    /// Submit the current input
    SubmitInput,
    /// Cancel the current input operation
    CancelInput,

    // === Text Editing ===
    /// Insert a character at cursor position
    InsertChar(char),
    /// Delete character before cursor (backspace)
    DeleteCharBackward,
    /// Delete character at cursor (delete)
    DeleteCharForward,
    /// Move cursor left
    MoveCursorLeft,
    /// Move cursor right
    MoveCursorRight,
    /// Move cursor to start of line
    MoveCursorStart,
    /// Move cursor to end of line
    MoveCursorEnd,

    // === Debug View (tui-logger) ===
    /// Send event to tui-logger widget
    LoggerEvent(TuiLoggerEvent),

    // === Application ===
    /// Quit the application
    Quit,
    /// Force quit without confirmation
    ForceQuit,
    /// Refresh data from database
    Refresh,
}

/// Events for the tui-logger debug view.
///
/// These map to [`TuiWidgetEvent`] for controlling the log viewer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TuiLoggerEvent {
    /// Toggle focus between target selector and logs
    SpaceBar,
    /// Scroll up through targets
    Up,
    /// Scroll down through targets
    Down,
    /// Move to previous page of logs
    PrevPage,
    /// Move to next page of logs
    NextPage,
    /// Decrease logging level for selected target
    Left,
    /// Increase logging level for selected target
    Right,
    /// Enable all log levels for selected target
    Plus,
    /// Disable all log levels for selected target
    Minus,
    /// Hide selected target
    Hide,
}

impl From<TuiLoggerEvent> for TuiWidgetEvent {
    fn from(event: TuiLoggerEvent) -> Self {
        match event {
            TuiLoggerEvent::SpaceBar => TuiWidgetEvent::SpaceKey,
            TuiLoggerEvent::Up => TuiWidgetEvent::UpKey,
            TuiLoggerEvent::Down => TuiWidgetEvent::DownKey,
            TuiLoggerEvent::PrevPage => TuiWidgetEvent::PrevPageKey,
            TuiLoggerEvent::NextPage => TuiWidgetEvent::NextPageKey,
            TuiLoggerEvent::Left => TuiWidgetEvent::LeftKey,
            TuiLoggerEvent::Right => TuiWidgetEvent::RightKey,
            TuiLoggerEvent::Plus => TuiWidgetEvent::PlusKey,
            TuiLoggerEvent::Minus => TuiWidgetEvent::MinusKey,
            TuiLoggerEvent::Hide => TuiWidgetEvent::HideKey,
        }
    }
}

impl Command {
    /// Executes the command, modifying the application state.
    ///
    /// # Arguments
    ///
    /// * `app` - The application state to modify
    ///
    /// # Returns
    ///
    /// Returns `Ok(true)` if the application should continue running,
    /// or `Ok(false)` if the application should quit.
    ///
    /// # Errors
    ///
    /// Returns an error if a database operation fails.
    pub async fn execute(self, app: &mut App) -> Result<bool, AppError> {
        debug!("Executing command: {:?}", self);

        match self {
            // === Navigation ===
            Command::NavigateUp => {
                match app.focus {
                    FocusPanel::TaskList => app.select_previous_task(),
                    FocusPanel::Sidebar => app.select_previous_project(),
                }
                Ok(true)
            }

            Command::NavigateDown => {
                match app.focus {
                    FocusPanel::TaskList => app.select_next_task(),
                    FocusPanel::Sidebar => app.select_next_project(),
                }
                Ok(true)
            }

            Command::NavigateTop => {
                if app.focus == FocusPanel::TaskList {
                    let count = app.visible_tasks().len();
                    if count > 0 {
                        app.selected_task_index = Some(0);
                    }
                } else {
                    app.selected_project_index = 0;
                }
                Ok(true)
            }

            Command::NavigateBottom => {
                if app.focus == FocusPanel::TaskList {
                    let count = app.visible_tasks().len();
                    if count > 0 {
                        app.selected_task_index = Some(count - 1);
                    }
                } else {
                    let count = app.projects.len() + 1; // +1 for "All Tasks"
                    app.selected_project_index = count - 1;
                }
                Ok(true)
            }

            Command::PageDown => {
                // Move down by 10 items or to the end
                if app.focus == FocusPanel::TaskList {
                    let count = app.visible_tasks().len();
                    if count > 0 {
                        let current = app.selected_task_index.unwrap_or(0);
                        app.selected_task_index = Some((current + 10).min(count - 1));
                    }
                }
                Ok(true)
            }

            Command::PageUp => {
                // Move up by 10 items or to the start
                if app.focus == FocusPanel::TaskList {
                    let count = app.visible_tasks().len();
                    if count > 0 {
                        let current = app.selected_task_index.unwrap_or(0);
                        app.selected_task_index = Some(current.saturating_sub(10));
                    }
                }
                Ok(true)
            }

            Command::SwitchPanel => {
                app.toggle_focus();
                Ok(true)
            }

            Command::FocusSidebar => {
                app.focus = FocusPanel::Sidebar;
                Ok(true)
            }

            Command::FocusTaskList => {
                app.focus = FocusPanel::TaskList;
                Ok(true)
            }

            // === Task Actions ===
            Command::AddTask => {
                // Open the add task dialog with available tags for autocomplete
                let mut dialog = AddTaskDialog::new().with_available_tags(app.tags.clone());

                // Set the project to the currently selected project (if not "All Tasks")
                if let Some(project) = app.selected_project() {
                    dialog.project_id = Some(project.id.clone());
                }

                app.dialog = Some(Dialog::AddTask(Box::new(dialog)));
                app.animation.start_dialog_open();
                app.set_status("Tab between fields, Ctrl+Enter to save");
                Ok(true)
            }

            Command::QuickCapture => {
                let mut dialog = QuickCaptureDialog::new(
                    app.projects.clone(),
                    app.tags.clone(),
                    &app.tasks,
                );

                // Pre-select the current project (if not "All Tasks")
                if let Some(project) = app.selected_project() {
                    dialog.set_project(project.clone());
                }

                app.dialog = Some(Dialog::QuickCapture(Box::new(dialog)));
                app.animation.start_quick_capture_open();
                app.set_status("Enter/submit  Tab/expand  Esc/cancel");
                Ok(true)
            }

            Command::EditTask => {
                if let Some(task) = app.selected_task().cloned() {
                    // Open the add task dialog in edit mode with available tags
                    let dialog = AddTaskDialog::from_task(&task).with_available_tags(app.tags.clone());
                    app.dialog = Some(Dialog::AddTask(Box::new(dialog)));
                    app.animation.start_dialog_open();
                    app.set_status("Tab between fields, Ctrl+Enter to save");
                }
                Ok(true)
            }

            Command::DeleteTask => {
                if let Some(task) = app.selected_task() {
                    // Open confirmation dialog
                    app.dialog = Some(Dialog::Confirm(ConfirmDialog::delete_task(&task.title)));
                    app.animation.start_dialog_open();
                }
                Ok(true)
            }

            Command::ToggleTaskStatus => {
                if let Some(task) = app.selected_task() {
                    let mut task = task.clone();
                    let completing = task.status != crate::models::TaskStatus::Completed;
                    if completing {
                        task.complete();
                        app.set_status("Task completed!");
                        app.pending_complete_animation = Some(task.id.clone());
                    } else {
                        task.reopen();
                        app.set_status("Task reopened");
                    }
                    app.db.update_task(&task).await?;
                    app.update_task_in_place(task);
                }
                Ok(true)
            }

            Command::CyclePriority => {
                if let Some(task) = app.selected_task() {
                    let mut task = task.clone();
                    task.priority = match task.priority {
                        Priority::Low => Priority::Medium,
                        Priority::Medium => Priority::High,
                        Priority::High => Priority::Urgent,
                        Priority::Urgent => Priority::Low,
                    };
                    let priority_color = match task.priority {
                        Priority::Urgent => crate::ui::theme::PRIORITY_URGENT,
                        Priority::High => crate::ui::theme::PRIORITY_HIGH,
                        Priority::Medium => crate::ui::theme::PRIORITY_NORMAL,
                        Priority::Low => crate::ui::theme::PRIORITY_LOW,
                    };
                    app.pending_priority_animation = Some((task.id.clone(), priority_color));
                    app.db.update_task(&task).await?;
                    app.set_status(format!("Priority: {:?}", task.priority));
                    app.update_task_in_place(task);
                }
                Ok(true)
            }

            Command::MoveToProject => {
                if let Some(task) = app.selected_task() {
                    let dialog = MoveToProjectDialog::new(
                        app.projects.clone(),
                        task.id.clone(),
                        task.project_id.as_deref(),
                    );
                    app.dialog = Some(Dialog::MoveToProject(dialog));
                    app.animation.start_dialog_open();
                    app.set_status("Select project to move task to");
                }
                Ok(true)
            }

            Command::EditTags => {
                // Edit tags by opening the task dialog focused on tags field
                if let Some(task) = app.selected_task().cloned() {
                    let dialog = AddTaskDialog::from_task(&task).with_available_tags(app.tags.clone());
                    app.dialog = Some(Dialog::AddTask(Box::new(dialog)));
                    app.animation.start_dialog_open();
                    app.set_status("Tab to Tags field, Enter to add tags");
                }
                Ok(true)
            }

            Command::AddProject => {
                app.dialog = Some(Dialog::Project(ProjectDialog::new()));
                app.animation.start_dialog_open();
                app.set_status("Enter project name, Tab to navigate");
                Ok(true)
            }

            Command::EditProject => {
                // Edit the currently selected project (not "All Tasks")
                if app.selected_project_index > 0 {
                    if let Some(project) = app.selected_project().cloned() {
                        app.dialog = Some(Dialog::Project(ProjectDialog::from_project(&project)));
                        app.animation.start_dialog_open();
                        app.set_status("Edit project, Tab to navigate");
                    }
                } else {
                    app.set_status("Select a project to edit (not 'All Tasks')");
                }
                Ok(true)
            }

            Command::DeleteProject => {
                // Delete the currently selected project (not "All Tasks" or "Inbox")
                if app.selected_project_index > 0 {
                    if let Some(project) = app.selected_project().cloned() {
                        if project.id == "inbox" {
                            app.set_status("Cannot delete the Inbox project");
                        } else {
                            let task_count = app.task_count_for_project(&project.id);
                            app.dialog = Some(Dialog::DeleteProject(
                                DeleteProjectDialog::new(
                                    project.id,
                                    project.name,
                                    task_count,
                                ),
                            ));
                            app.animation.start_dialog_open();
                        }
                    }
                } else {
                    app.set_status("Select a project to delete");
                }
                Ok(true)
            }

            // === Views ===
            Command::ShowMain => {
                app.current_view = View::Main;
                app.animation.start_view_transition();
                Ok(true)
            }

            Command::ShowHelp => {
                app.current_view = View::Help;
                app.animation.start_view_transition();
                Ok(true)
            }

            Command::ShowCalendar => {
                app.current_view = View::Calendar;
                // Reset calendar to today when opening
                app.calendar_state.goto_today();
                app.animation.start_view_transition();
                Ok(true)
            }

            // === Calendar Navigation ===
            Command::CalendarPrevDay => {
                app.calendar_state.prev_day();
                Ok(true)
            }

            Command::CalendarNextDay => {
                app.calendar_state.next_day();
                Ok(true)
            }

            Command::CalendarPrevWeek => {
                app.calendar_state.prev_week();
                Ok(true)
            }

            Command::CalendarNextWeek => {
                app.calendar_state.next_week();
                Ok(true)
            }

            Command::CalendarToday => {
                app.calendar_state.goto_today();
                Ok(true)
            }

            Command::CalendarSelectDay => {
                // Return to main view - filter could be applied for selected day
                app.current_view = View::Main;
                app.animation.start_view_transition();
                Ok(true)
            }

            Command::CalendarToggleFocus => {
                app.calendar_state.toggle_focus();
                Ok(true)
            }

            Command::CalendarTaskUp => {
                app.calendar_state.prev_task();
                Ok(true)
            }

            Command::CalendarTaskDown => {
                let task_count = crate::ui::calendar::get_task_count_for_selected_day(app);
                app.calendar_state.next_task(task_count);
                Ok(true)
            }

            Command::CalendarToggleTask => {
                let task_ids = crate::ui::calendar::get_tasks_for_selected_day(app);
                if let Some(task_id) = task_ids.get(app.calendar_state.selected_task_index)
                    && let Some(task) = app.tasks.iter().find(|t| &t.id == task_id)
                {
                    let mut task = task.clone();
                    if task.status == crate::models::TaskStatus::Completed {
                        task.reopen();
                        app.set_status("Task reopened");
                    } else {
                        task.complete();
                        app.set_status("Task completed!");
                    }
                    app.db.update_task(&task).await?;
                    app.update_task_in_place(task);
                }
                Ok(true)
            }

            Command::CalendarCyclePriority => {
                let task_ids = crate::ui::calendar::get_tasks_for_selected_day(app);
                if let Some(task_id) = task_ids.get(app.calendar_state.selected_task_index)
                    && let Some(task) = app.tasks.iter().find(|t| &t.id == task_id)
                {
                    let mut task = task.clone();
                    task.priority = match task.priority {
                        Priority::Low => Priority::Medium,
                        Priority::Medium => Priority::High,
                        Priority::High => Priority::Urgent,
                        Priority::Urgent => Priority::Low,
                    };
                    app.db.update_task(&task).await?;
                    app.set_status(format!("Priority: {:?}", task.priority));
                    app.update_task_in_place(task);
                }
                Ok(true)
            }

            Command::CalendarEditTask => {
                let task_ids = crate::ui::calendar::get_tasks_for_selected_day(app);
                if let Some(task_id) = task_ids.get(app.calendar_state.selected_task_index)
                    && let Some(task) = app.tasks.iter().find(|t| &t.id == task_id)
                {
                    let dialog = AddTaskDialog::from_task(task).with_available_tags(app.tags.clone());
                    app.dialog = Some(Dialog::AddTask(Box::new(dialog)));
                    app.set_status("Tab between fields, Ctrl+Enter to save");
                }
                Ok(true)
            }

            Command::CalendarGoToTask => {
                let task_ids = crate::ui::calendar::get_tasks_for_selected_day(app);
                if let Some(task_id) = task_ids.get(app.calendar_state.selected_task_index)
                    && let Some(task) = app.tasks.iter().find(|t| &t.id == task_id)
                {
                    let task_id = task.id.clone();
                    let project_id = task.project_id.clone();

                    // Switch to main view
                    app.current_view = View::Main;
                    app.animation.start_view_transition();
                    app.focus = FocusPanel::TaskList;

                    // Select the project in the sidebar
                    if let Some(pid) = &project_id {
                        // Find the project index and select it
                        if let Some(idx) = app.projects.iter().position(|p| &p.id == pid) {
                            // Add 1 because index 0 is "All Tasks"
                            app.selected_project_index = idx + 1;
                        }
                    } else {
                        // No project - select "All Tasks"
                        app.selected_project_index = 0;
                    }

                    // Clear filter to ensure task is visible
                    app.filter = Filter::All;

                    // Find and select the task
                    if let Some(idx) = app.visible_tasks().iter().position(|t| t.id == task_id) {
                        app.selected_task_index = Some(idx);
                    }

                    // Reset calendar focus for next time
                    app.calendar_state.focus = crate::ui::calendar::CalendarFocus::DayGrid;
                }
                Ok(true)
            }

            Command::CalendarToggleCompleted => {
                app.calendar_state.toggle_show_completed();
                let status = if app.calendar_state.show_completed {
                    "Showing all tasks"
                } else {
                    "Showing active tasks only"
                };
                app.set_status(status);
                Ok(true)
            }

            Command::ShowSearch => {
                app.current_view = View::Search;
                app.input_mode = InputMode::Search;
                app.input_buffer.clear();
                app.input_cursor = 0;
                app.search_results.clear();
                app.selected_search_index = 0;
                app.animation.start_view_transition();
                let project_name = app.selected_project_name().to_string();
                if project_name != "All Tasks" {
                    app.set_status(format!("Searching in: {}", project_name));
                }
                Ok(true)
            }

            Command::SearchNavigateUp => {
                if !app.search_results.is_empty() {
                    app.selected_search_index = app.selected_search_index.saturating_sub(1);
                }
                Ok(true)
            }

            Command::SearchNavigateDown => {
                if !app.search_results.is_empty() {
                    app.selected_search_index =
                        (app.selected_search_index + 1).min(app.search_results.len() - 1);
                }
                Ok(true)
            }

            Command::SearchSelectTask => {
                if let Some(result) = app.search_results.get(app.selected_search_index) {
                    // Find the task index in visible_tasks and select it
                    let task_id = result.task.id.clone();
                    app.current_view = View::Main;
                    app.animation.start_view_transition();
                    app.input_mode = InputMode::Normal;
                    app.input_buffer.clear();
                    app.input_cursor = 0;
                    // Focus the task list panel
                    app.focus = FocusPanel::TaskList;

                    // Try to find and select the task
                    if let Some(idx) = app
                        .visible_tasks()
                        .iter()
                        .position(|t| t.id == task_id)
                    {
                        app.selected_task_index = Some(idx);
                    } else {
                        // Task might not be visible due to filters, clear filter
                        app.filter = Filter::All;
                        if let Some(idx) = app
                            .visible_tasks()
                            .iter()
                            .position(|t| t.id == task_id)
                        {
                            app.selected_task_index = Some(idx);
                        }
                    }
                    app.set_status(format!("Selected: {}", result.task.title));
                }
                Ok(true)
            }

            Command::ShowDebugLogs => {
                app.current_view = if app.current_view == View::DebugLogs {
                    View::Main
                } else {
                    View::DebugLogs
                };
                app.animation.start_view_transition();
                Ok(true)
            }

            Command::ShowTaskDetail => {
                if app.selected_task().is_some() {
                    app.current_view = View::TaskDetail;
                    app.animation.start_view_transition();
                }
                Ok(true)
            }

            // === Filters ===
            Command::SetFilter(filter) => {
                app.filter = filter;
                // Reset selection when filter changes
                let count = app.visible_tasks().len();
                app.selected_task_index = if count > 0 { Some(0) } else { None };
                Ok(true)
            }

            Command::ShowFilterSort => {
                // Use project-scoped tasks for filter counts
                let project_tasks: Vec<Task> = app.project_tasks().into_iter().cloned().collect();
                app.dialog = Some(Dialog::FilterSort(FilterSortDialog::new(
                    &app.filter,
                    &app.sort,
                    &project_tasks,
                )));
                app.animation.start_dialog_open();
                Ok(true)
            }

            Command::ShowSettings => {
                app.dialog = Some(Dialog::Settings(SettingsDialog::new()));
                app.animation.start_dialog_open();
                Ok(true)
            }

            Command::FilterToday => {
                app.filter = Filter::DueToday;
                let count = app.visible_tasks().len();
                app.selected_task_index = if count > 0 { Some(0) } else { None };
                app.set_status("Showing tasks due today");
                Ok(true)
            }

            Command::FilterThisWeek => {
                app.filter = Filter::DueThisWeek;
                let count = app.visible_tasks().len();
                app.selected_task_index = if count > 0 { Some(0) } else { None };
                app.set_status("Showing tasks due this week");
                Ok(true)
            }

            Command::FilterByPriority(priority) => {
                app.filter = Filter::ByPriority(priority);
                let count = app.visible_tasks().len();
                app.selected_task_index = if count > 0 { Some(0) } else { None };
                app.set_status(format!("Showing {:?} priority tasks", priority));
                Ok(true)
            }

            // === Input Mode ===
            Command::EnterEditMode => {
                app.input_mode = InputMode::Editing;
                Ok(true)
            }

            Command::ExitEditMode => {
                app.input_mode = InputMode::Normal;
                app.input_buffer.clear();
                app.input_cursor = 0;
                app.editing_task = None;
                app.clear_status();
                Ok(true)
            }

            Command::SubmitInput => {
                if app.input_mode == InputMode::Editing {
                    let title = app.input_buffer.trim().to_string();
                    if !title.is_empty() {
                        if let Some(mut task) = app.editing_task.take() {
                            // Editing existing task
                            task.title = title;
                            app.db.update_task(&task).await?;
                            app.set_status("Task updated");
                        } else {
                            // Creating new task
                            let task = crate::models::Task::new(&title);
                            app.db.insert_task(&task).await?;
                            app.set_status("Task added");
                        }
                        app.load_data().await?;
                    }
                }
                app.input_mode = InputMode::Normal;
                app.input_buffer.clear();
                app.input_cursor = 0;
                Ok(true)
            }

            Command::CancelInput => {
                // Return to main view if in search
                if app.current_view == View::Search {
                    app.current_view = View::Main;
                    app.animation.start_view_transition();
                    app.search_results.clear();
                    app.selected_search_index = 0;
                }
                app.input_mode = InputMode::Normal;
                app.input_buffer.clear();
                app.input_cursor = 0;
                app.editing_task = None;
                app.clear_status();
                Ok(true)
            }

            // === Text Editing ===
            Command::InsertChar(c) => {
                app.input_buffer.insert(app.input_cursor, c);
                app.input_cursor += 1;
                // Update search results if in search mode (scoped to current project)
                if app.input_mode == InputMode::Search {
                    let project_tasks: Vec<Task> = app.project_tasks().into_iter().cloned().collect();
                    app.search_results = search_tasks(&app.input_buffer, &project_tasks);
                    app.selected_search_index = 0;
                }
                Ok(true)
            }

            Command::DeleteCharBackward => {
                if app.input_cursor > 0 {
                    app.input_cursor -= 1;
                    app.input_buffer.remove(app.input_cursor);
                    // Update search results if in search mode (scoped to current project)
                    if app.input_mode == InputMode::Search {
                        let project_tasks: Vec<Task> = app.project_tasks().into_iter().cloned().collect();
                        app.search_results = search_tasks(&app.input_buffer, &project_tasks);
                        app.selected_search_index = 0;
                    }
                }
                Ok(true)
            }

            Command::DeleteCharForward => {
                if app.input_cursor < app.input_buffer.len() {
                    app.input_buffer.remove(app.input_cursor);
                }
                Ok(true)
            }

            Command::MoveCursorLeft => {
                app.input_cursor = app.input_cursor.saturating_sub(1);
                Ok(true)
            }

            Command::MoveCursorRight => {
                if app.input_cursor < app.input_buffer.len() {
                    app.input_cursor += 1;
                }
                Ok(true)
            }

            Command::MoveCursorStart => {
                app.input_cursor = 0;
                Ok(true)
            }

            Command::MoveCursorEnd => {
                app.input_cursor = app.input_buffer.len();
                Ok(true)
            }

            // === Debug View ===
            Command::LoggerEvent(event) => {
                app.log_state.transition(TuiWidgetEvent::from(event));
                Ok(true)
            }

            // === Application ===
            Command::Quit => {
                app.should_quit = true;
                Ok(false)
            }

            Command::ForceQuit => {
                app.should_quit = true;
                Ok(false)
            }

            Command::Refresh => {
                app.load_data().await?;
                app.set_status("Data refreshed");
                Ok(true)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::Task;
    use crate::storage::{run_migrations, Database};

    async fn setup_app() -> App {
        let db = Database::open_in_memory().await.unwrap();
        run_migrations(&db).await.unwrap();
        App::new(db).await.unwrap()
    }

    async fn setup_app_with_tasks() -> App {
        let mut app = setup_app().await;
        for i in 0..5 {
            let task = Task::new(&format!("Task {}", i));
            app.db.insert_task(&task).await.unwrap();
        }
        app.load_data().await.unwrap();
        app
    }

    #[tokio::test]
    async fn test_navigate_down() {
        let mut app = setup_app_with_tasks().await;
        app.selected_task_index = Some(0);

        Command::NavigateDown.execute(&mut app).await.unwrap();
        assert_eq!(app.selected_task_index, Some(1));
    }

    #[tokio::test]
    async fn test_navigate_up() {
        let mut app = setup_app_with_tasks().await;
        app.selected_task_index = Some(2);

        Command::NavigateUp.execute(&mut app).await.unwrap();
        assert_eq!(app.selected_task_index, Some(1));
    }

    #[tokio::test]
    async fn test_navigate_top() {
        let mut app = setup_app_with_tasks().await;
        app.selected_task_index = Some(3);

        Command::NavigateTop.execute(&mut app).await.unwrap();
        assert_eq!(app.selected_task_index, Some(0));
    }

    #[tokio::test]
    async fn test_navigate_bottom() {
        let mut app = setup_app_with_tasks().await;
        app.selected_task_index = Some(0);

        Command::NavigateBottom.execute(&mut app).await.unwrap();
        assert_eq!(app.selected_task_index, Some(4)); // 5 tasks, index 4
    }

    #[tokio::test]
    async fn test_switch_panel() {
        let mut app = setup_app().await;
        assert_eq!(app.focus, FocusPanel::TaskList);

        Command::SwitchPanel.execute(&mut app).await.unwrap();
        assert_eq!(app.focus, FocusPanel::Sidebar);

        Command::SwitchPanel.execute(&mut app).await.unwrap();
        assert_eq!(app.focus, FocusPanel::TaskList);
    }

    #[tokio::test]
    async fn test_quit_command() {
        let mut app = setup_app().await;
        assert!(!app.should_quit);

        let result = Command::Quit.execute(&mut app).await.unwrap();
        assert!(!result); // Returns false to stop loop
        assert!(app.should_quit);
    }

    #[tokio::test]
    async fn test_show_help() {
        let mut app = setup_app().await;
        app.current_view = View::Main;

        Command::ShowHelp.execute(&mut app).await.unwrap();
        assert_eq!(app.current_view, View::Help);
    }

    #[tokio::test]
    async fn test_show_main() {
        let mut app = setup_app().await;
        app.current_view = View::Help;

        Command::ShowMain.execute(&mut app).await.unwrap();
        assert_eq!(app.current_view, View::Main);
    }

    #[tokio::test]
    async fn test_toggle_debug_logs() {
        let mut app = setup_app().await;
        app.current_view = View::Main;

        Command::ShowDebugLogs.execute(&mut app).await.unwrap();
        assert_eq!(app.current_view, View::DebugLogs);

        Command::ShowDebugLogs.execute(&mut app).await.unwrap();
        assert_eq!(app.current_view, View::Main);
    }

    #[tokio::test]
    async fn test_toggle_task_status() {
        use crate::models::{Filter, TaskStatus};

        let mut app = setup_app().await;
        // Use All filter so completed tasks remain visible
        app.filter = Filter::All;

        let task = Task::new("Test task");
        app.db.insert_task(&task).await.unwrap();
        app.load_data().await.unwrap();
        app.selected_task_index = Some(0);

        // Initial status is Pending
        assert_eq!(app.tasks[0].status, TaskStatus::Pending);

        // Toggle to completed
        Command::ToggleTaskStatus.execute(&mut app).await.unwrap();
        assert_eq!(app.tasks[0].status, TaskStatus::Completed);

        // Toggle back to pending
        Command::ToggleTaskStatus.execute(&mut app).await.unwrap();
        assert_eq!(app.tasks[0].status, TaskStatus::Pending);
    }

    #[tokio::test]
    async fn test_add_task_opens_dialog() {
        use crate::ui::dialogs::Dialog;

        let mut app = setup_app().await;
        assert!(app.dialog.is_none());

        Command::AddTask.execute(&mut app).await.unwrap();

        // Dialog should be open
        assert!(app.dialog.is_some());
        assert!(matches!(app.dialog, Some(Dialog::AddTask(_))));
    }

    #[tokio::test]
    async fn test_edit_task_opens_dialog() {
        use crate::ui::dialogs::Dialog;

        let mut app = setup_app().await;
        let task = Task::new("Original title");
        app.db.insert_task(&task).await.unwrap();
        app.load_data().await.unwrap();
        app.selected_task_index = Some(0);

        Command::EditTask.execute(&mut app).await.unwrap();

        // Dialog should be open with task data
        assert!(app.dialog.is_some());
        if let Some(Dialog::AddTask(ref dialog)) = app.dialog {
            assert_eq!(dialog.title.value(), "Original title");
            assert!(dialog.is_editing());
        } else {
            panic!("Expected AddTask dialog");
        }
    }

    #[tokio::test]
    async fn test_delete_task_opens_confirm_dialog() {
        use crate::ui::dialogs::Dialog;

        let mut app = setup_app().await;
        let task = Task::new("Delete me");
        app.db.insert_task(&task).await.unwrap();
        app.load_data().await.unwrap();
        assert_eq!(app.tasks.len(), 1);
        app.selected_task_index = Some(0);

        Command::DeleteTask.execute(&mut app).await.unwrap();

        // Confirm dialog should be open, task not yet deleted
        assert!(app.dialog.is_some());
        assert!(matches!(app.dialog, Some(Dialog::Confirm(_))));
        assert_eq!(app.tasks.len(), 1); // Not deleted until confirmed
    }

    #[tokio::test]
    async fn test_cycle_priority() {
        let mut app = setup_app().await;
        let task = Task::new("Priority test");
        app.db.insert_task(&task).await.unwrap();
        app.load_data().await.unwrap();
        app.selected_task_index = Some(0);

        assert_eq!(app.tasks[0].priority, Priority::Medium); // Default

        Command::CyclePriority.execute(&mut app).await.unwrap();
        assert_eq!(app.tasks[0].priority, Priority::High);

        Command::CyclePriority.execute(&mut app).await.unwrap();
        assert_eq!(app.tasks[0].priority, Priority::Urgent);

        Command::CyclePriority.execute(&mut app).await.unwrap();
        assert_eq!(app.tasks[0].priority, Priority::Low);
    }

    #[tokio::test]
    async fn test_filter_today() {
        let mut app = setup_app().await;

        Command::FilterToday.execute(&mut app).await.unwrap();
        assert_eq!(app.filter, Filter::DueToday);
    }

    #[tokio::test]
    async fn test_show_filter_sort() {
        let mut app = setup_app().await;

        Command::ShowFilterSort.execute(&mut app).await.unwrap();
        assert!(matches!(app.dialog, Some(Dialog::FilterSort(_))));
    }

    #[tokio::test]
    async fn test_text_editing_commands() {
        let mut app = setup_app().await;
        app.input_mode = InputMode::Editing;

        // Insert characters
        Command::InsertChar('H').execute(&mut app).await.unwrap();
        Command::InsertChar('i').execute(&mut app).await.unwrap();
        assert_eq!(app.input_buffer, "Hi");
        assert_eq!(app.input_cursor, 2);

        // Move cursor left
        Command::MoveCursorLeft.execute(&mut app).await.unwrap();
        assert_eq!(app.input_cursor, 1);

        // Insert at cursor
        Command::InsertChar('o').execute(&mut app).await.unwrap();
        assert_eq!(app.input_buffer, "Hoi");
        assert_eq!(app.input_cursor, 2);

        // Backspace
        Command::DeleteCharBackward.execute(&mut app).await.unwrap();
        assert_eq!(app.input_buffer, "Hi");
        assert_eq!(app.input_cursor, 1);
    }

    #[tokio::test]
    async fn test_submit_new_task() {
        let mut app = setup_app().await;
        app.input_mode = InputMode::Editing;
        app.input_buffer = "New task from test".to_string();
        app.input_cursor = app.input_buffer.len();

        Command::SubmitInput.execute(&mut app).await.unwrap();

        assert_eq!(app.input_mode, InputMode::Normal);
        assert!(app.input_buffer.is_empty());
        assert_eq!(app.tasks.len(), 1);
        assert_eq!(app.tasks[0].title, "New task from test");
    }

    #[tokio::test]
    async fn test_cancel_input() {
        let mut app = setup_app().await;
        app.input_mode = InputMode::Editing;
        app.input_buffer = "Some text".to_string();

        Command::CancelInput.execute(&mut app).await.unwrap();

        assert_eq!(app.input_mode, InputMode::Normal);
        assert!(app.input_buffer.is_empty());
    }

    #[tokio::test]
    async fn test_refresh() {
        let mut app = setup_app().await;

        // Add a task directly to DB
        let task = Task::new("Direct insert");
        app.db.insert_task(&task).await.unwrap();

        // App doesn't know about it yet
        assert!(app.tasks.is_empty());

        // Refresh should load it
        Command::Refresh.execute(&mut app).await.unwrap();
        assert_eq!(app.tasks.len(), 1);
    }

    #[tokio::test]
    async fn test_quick_capture_opens_dialog() {
        use crate::ui::dialogs::Dialog;

        let mut app = setup_app().await;
        assert!(app.dialog.is_none());

        Command::QuickCapture.execute(&mut app).await.unwrap();

        assert!(app.dialog.is_some());
        assert!(matches!(app.dialog, Some(Dialog::QuickCapture(_))));
    }

    #[tokio::test]
    async fn test_quick_capture_preselects_project() {
        use crate::models::Project;
        use crate::ui::dialogs::Dialog;

        let mut app = setup_app().await;

        // Create a project and select it in the sidebar
        let project = Project::new("Backend");
        app.db.insert_project(&project).await.unwrap();
        app.projects = app.db.get_all_projects().await.unwrap();
        // Index 0 = "All Tasks", index 1 = first project
        app.selected_project_index = 1;

        Command::QuickCapture.execute(&mut app).await.unwrap();

        // Dialog should have the project pre-selected
        if let Some(Dialog::QuickCapture(ref dialog)) = app.dialog {
            assert!(dialog.project().is_some());
            assert_eq!(dialog.project().unwrap().name, "Backend");
        } else {
            panic!("Expected QuickCapture dialog");
        }
    }

    #[tokio::test]
    async fn test_quick_capture_no_project_when_all_tasks() {
        use crate::ui::dialogs::Dialog;

        let mut app = setup_app().await;
        // "All Tasks" is selected (index 0)
        app.selected_project_index = 0;

        Command::QuickCapture.execute(&mut app).await.unwrap();

        // Dialog should have no project pre-selected
        if let Some(Dialog::QuickCapture(ref dialog)) = app.dialog {
            assert!(dialog.project().is_none());
        } else {
            panic!("Expected QuickCapture dialog");
        }
    }
}