budget_tracker_tui 1.4.1

A feature rich TUI budget tracker app
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
use crate::app::update_checker;
use crate::config::{AppSettings, load_settings};
use crate::csv_io::{load_seed_categories, load_transactions};
use crate::db::category_store::{CategoryStore, SqliteCategoryStore};
use crate::db::database::SqliteDatabase;
use crate::db::transaction_store::{SqliteTransactionStore, TransactionStore};
use crate::model::*;
use chrono::{Datelike, Duration, NaiveDate};
use ratatui::widgets::{ListState, TableState};
use rust_decimal::Decimal;
use std::collections::{HashMap, HashSet};
use std::fs::{copy, create_dir_all};
use std::io::{Error, ErrorKind};
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::thread;

pub(crate) enum DateUnit {
    Day,
    Month,
}

#[derive(PartialEq, Debug, Clone, Copy)]
pub enum AppMode {
    Normal,
    Adding,
    Editing,
    ConfirmDelete,
    Filtering,
    AdvancedFiltering,
    SelectingFilterCategory,
    SelectingFilterSubcategory,
    Summary,
    SelectingCategory,
    SelectingSubcategory,
    CategorySummary,
    Budget,
    Settings,
    RecurringSettings,
    SelectingRecurrenceFrequency,
    KeybindingsInfo,
    KeybindingDetail,
    FuzzyFinding,
    CategoryCatalog,
    CategoryCatalogFilter,
    CategoryEditor,
    ConfirmCategoryDelete,
    ImportTransactions,
    ExportTransactions,
}

#[derive(Debug)]
pub enum CategorySummaryItem {
    Month(u32, MonthlySummary),
    Subcategory(u32, String, String, MonthlySummary),
}

#[derive(Debug, Clone)]
pub struct BudgetCategoryComparison {
    pub category: String,
    pub subcategory: String,
    pub target_budget: Decimal,
    pub actual_expense: Decimal,
}

pub struct App {
    pub(crate) transactions: Vec<Transaction>,
    pub(crate) filtered_indices: Vec<usize>,
    pub(crate) categories: Vec<CategoryInfo>,
    pub(crate) category_records: Vec<CategoryRecord>,
    pub(crate) data_file_path: PathBuf,
    pub(crate) database_path: PathBuf,
    pub(crate) should_quit: bool,
    pub(crate) table_state: TableState,
    pub(crate) mode: AppMode,
    pub(crate) simple_filter_content: String,
    pub(crate) simple_filter_cursor: usize,
    pub(crate) add_edit_fields: [String; 6],
    pub(crate) current_add_edit_field: usize,
    pub(crate) add_edit_cursor: usize,
    pub(crate) advanced_filter_fields: [String; 8],
    pub(crate) current_advanced_filter_field: usize,
    pub(crate) advanced_filter_cursor: usize,
    pub(crate) delete_index: Option<usize>,
    pub(crate) editing_index: Option<usize>,
    pub(crate) status_message: Option<String>,
    pub(crate) status_expiry: Option<std::time::Instant>,
    pub(crate) sort_by: SortColumn,
    pub(crate) sort_order: SortOrder,
    // Monthly Summary State
    pub(crate) monthly_summaries: HashMap<(i32, u32), MonthlySummary>,
    pub(crate) summary_years: Vec<i32>,
    pub(crate) selected_summary_year_index: usize,
    pub(crate) selected_summary_month: Option<u32>,
    pub(crate) summary_multi_month_mode: bool,
    pub(crate) summary_cumulative_mode: bool,
    // Category/Subcategory Selection Popup State
    pub(crate) selecting_field_index: Option<usize>,
    pub(crate) current_selection_list: Vec<String>,
    pub(crate) selection_list_state: ListState,
    pub(crate) type_to_select: crate::app::util::TypeToSelect,
    // Category Summary State
    pub(crate) category_summary_table_state: TableState,
    pub(crate) category_summaries: HashMap<(i32, u32), HashMap<(String, String), MonthlySummary>>,
    pub(crate) category_summary_years: Vec<i32>,
    pub(crate) category_summary_year_index: usize,
    // Expansion state for hierarchical category summary
    pub(crate) expanded_category_summary_months: HashSet<u32>,
    // Flattened list of visible items for rendering and navigation
    pub(crate) cached_visible_category_items: Vec<CategorySummaryItem>,
    // Budget view state
    pub(crate) budget_years: Vec<i32>,
    pub(crate) budget_year_index: usize,
    pub(crate) selected_budget_month: Option<u32>,
    pub(crate) budget_table_state: TableState,
    // Settings form state
    pub(crate) settings_state: crate::app::settings_types::SettingsState,
    // Category catalog state
    pub(crate) category_table_state: TableState,
    pub(crate) filtered_category_indices: Vec<usize>,
    pub(crate) category_filter_query: String,
    pub(crate) category_filter_cursor: usize,
    pub(crate) category_edit_fields: [String; 5], // [type, category, subcategory, tag, target_budget]
    pub(crate) current_category_field: usize,
    pub(crate) category_edit_cursor: usize,
    pub(crate) editing_category_id: Option<i64>,
    pub(crate) category_delete_id: Option<i64>,
    // Mode to return to when leaving the category catalog (Settings or Budget)
    pub(crate) category_catalog_origin: AppMode,
    // Budget
    pub(crate) target_budget: Option<Decimal>,
    pub(crate) hourly_rate: Option<Decimal>,
    pub(crate) show_hours: bool,
    pub(crate) fuzzy_search_mode: bool,
    pub(crate) search_query: String,
    // Recurring transaction state
    pub(crate) recurring_settings_fields: [String; 3], // [is_recurring, frequency, end_date]
    pub(crate) current_recurring_field: usize,
    pub(crate) recurring_transaction_index: Option<usize>,
    // Import/Export path prompt state (shared by ImportTransactions/ExportTransactions modes)
    pub(crate) io_path_input: String,
    pub(crate) io_path_cursor: usize,
    // Help/Keybindings
    pub(crate) previous_mode: Option<AppMode>,
    pub(crate) help_table_state: TableState,
    pub(crate) hide_help_bar: bool,
    // Update Check
    pub(crate) update_available_version: Option<String>,
    pub(crate) show_update_popup: bool,
    pub(crate) update_rx: mpsc::Receiver<Option<String>>,
}

impl App {
    pub fn new() -> Self {
        // --- Start Update Check ---
        let (tx, rx) = mpsc::channel();
        thread::spawn(move || {
            let result = update_checker::check_for_updates();
            let _ = tx.send(result);
        });

        // --- Load Settings ---
        let (loaded_settings, load_settings_error_msg) = match load_settings() {
            Ok(settings) => (settings, None),
            Err(e) => (
                AppSettings::default(),
                Some(format!("Config Load Error: {}. Using defaults.", e)),
            ),
        };

        let (initial_data_file_path, data_path_error_msg) = Self::resolve_configured_path(
            loaded_settings.data_file_path.clone(),
            Self::get_default_data_file_path,
            "transactions.csv",
            "Data file",
        );
        let (initial_database_path, database_path_error_msg) =
            match loaded_settings.database_path.clone() {
                Some(path) => Self::resolve_configured_path(
                    Some(path),
                    Self::get_default_database_file_path,
                    "budget.db",
                    "Database",
                ),
                None => Self::resolve_default_database_path(&initial_data_file_path),
            };

        // --- Migrate legacy CSV into the database (one time), then load from the database ---
        let migration_msg =
            match Self::run_one_time_csv_migration(&initial_database_path, &initial_data_file_path)
            {
                Ok(msg) => msg,
                Err(e) => Some(format!("Transaction migration error: {}", e)),
            };
        let (mut transactions, load_tx_specific_error_msg) =
            match Self::transaction_store_for_path(&initial_database_path).list() {
                Ok(txs) => (txs, None),
                Err(e) => (
                    vec![],
                    Some(format!(
                        "Load TX Error [{}]: {}",
                        initial_database_path.display(),
                        e
                    )),
                ),
            };

        let (seed_categories, load_seed_error_msg) = match load_seed_categories() {
            Ok(cats) => (cats, None),
            Err(e) => (vec![], Some(format!("Embedded Category Seed Error: {}", e))),
        };
        let (category_records, load_cat_error_msg) =
            match Self::load_category_records(&initial_database_path, &seed_categories) {
                Ok(records) => (records, None),
                Err(e) => (
                    vec![],
                    Some(format!(
                        "Category DB Error [{}]: {}",
                        initial_database_path.display(),
                        e
                    )),
                ),
            };
        let categories = if category_records.is_empty() {
            seed_categories.clone()
        } else {
            Self::project_categories(&category_records)
        };

        // Combine potential errors (settings, paths, tx load, category load)
        let load_tx_error_msg = [
            load_settings_error_msg,
            data_path_error_msg,
            load_tx_specific_error_msg,
            database_path_error_msg,
            load_seed_error_msg,
            migration_msg,
        ]
        .into_iter()
        .flatten()
        .collect::<Vec<_>>()
        .join(" | ");
        let load_tx_error_msg = if load_tx_error_msg.is_empty() {
            None
        } else {
            Some(load_tx_error_msg)
        };

        // --- Combine All Load Errors ---
        let load_error_msg = match (load_tx_error_msg, load_cat_error_msg) {
            (Some(tx_err), Some(cat_err)) => Some(format!("{} | {}", tx_err, cat_err)),
            (Some(tx_err), None) => Some(tx_err),
            (None, Some(cat_err)) => Some(cat_err),
            (None, None) => None,
        };
        let initial_sort_by = SortColumn::Date;
        let initial_sort_order = SortOrder::Descending;
        crate::app::util::sort_transactions_impl(
            &mut transactions,
            initial_sort_by,
            initial_sort_order,
        );
        let initial_filtered_indices = (0..transactions.len()).collect();
        let initial_filtered_category_indices = (0..category_records.len()).collect();
        let mut app = Self {
            transactions,
            filtered_indices: initial_filtered_indices,
            categories,
            category_records,
            data_file_path: initial_data_file_path,
            database_path: initial_database_path,
            should_quit: false,
            table_state: TableState::default(),
            mode: AppMode::Normal,
            simple_filter_content: String::new(),
            simple_filter_cursor: 0,
            add_edit_fields: Default::default(),
            current_add_edit_field: 0,
            add_edit_cursor: 0,
            advanced_filter_fields: Default::default(),
            current_advanced_filter_field: 0,
            advanced_filter_cursor: 0,
            delete_index: None,
            editing_index: None,
            status_message: load_error_msg,
            status_expiry: None,
            sort_by: initial_sort_by,
            sort_order: initial_sort_order,
            monthly_summaries: HashMap::new(),
            summary_years: Vec::new(),
            selected_summary_year_index: 0,
            selected_summary_month: None,
            summary_multi_month_mode: false,
            summary_cumulative_mode: false,
            selecting_field_index: None,
            current_selection_list: Vec::new(),
            selection_list_state: ListState::default(),
            type_to_select: crate::app::util::TypeToSelect::new(),
            category_summaries: HashMap::new(),
            category_summary_years: Vec::new(),
            category_summary_year_index: 0,
            category_summary_table_state: TableState::default(),
            expanded_category_summary_months: HashSet::new(),
            cached_visible_category_items: Vec::new(),
            budget_years: Vec::new(),
            budget_year_index: 0,
            selected_budget_month: None,
            budget_table_state: TableState::default(),
            settings_state: crate::app::settings_types::SettingsState::default(),
            category_table_state: TableState::default(),
            filtered_category_indices: initial_filtered_category_indices,
            category_filter_query: String::new(),
            category_filter_cursor: 0,
            category_edit_fields: Default::default(),
            current_category_field: 0,
            category_edit_cursor: 0,
            editing_category_id: None,
            category_delete_id: None,
            category_catalog_origin: AppMode::Settings,
            target_budget: loaded_settings.target_budget,
            hourly_rate: loaded_settings.hourly_rate,
            show_hours: loaded_settings.show_hours.unwrap_or(false),
            fuzzy_search_mode: loaded_settings.fuzzy_search_mode.unwrap_or(false),
            search_query: String::new(),
            recurring_settings_fields: Default::default(),
            current_recurring_field: 0,
            recurring_transaction_index: None,
            io_path_input: String::new(),
            io_path_cursor: 0,
            previous_mode: None,
            help_table_state: TableState::default(),
            hide_help_bar: loaded_settings.hide_help_bar.unwrap_or(false),
            update_available_version: None,
            show_update_popup: false,
            update_rx: rx,
        };
        app.calculate_monthly_summaries();
        app.calculate_category_summaries();
        app.refresh_budget_years();
        if !app.summary_years.is_empty() {
            app.selected_summary_year_index = app.summary_years.len() - 1;
        }
        if !app.transactions.is_empty() {
            app.table_state.select(Some(0));
        }

        // Generate recurring transactions up to today
        app.generate_recurring_transactions();

        app
    }

    fn resolve_configured_path(
        configured_path: Option<String>,
        default_path_fn: fn() -> Result<PathBuf, Error>,
        fallback_name: &str,
        label: &str,
    ) -> (PathBuf, Option<String>) {
        match configured_path {
            Some(path_str) => {
                let path = PathBuf::from(path_str);
                if let Some(parent) = path.parent()
                    && let Err(err) = create_dir_all(parent)
                {
                    let fallback =
                        default_path_fn().unwrap_or_else(|_| PathBuf::from(fallback_name));
                    return (
                        fallback,
                        Some(format!(
                            "{} path error: Could not create parent dir for {}: {}. Using default.",
                            label,
                            path.display(),
                            err
                        )),
                    );
                }

                (path, None)
            }
            None => match default_path_fn() {
                Ok(path) => (path, None),
                Err(err) => (
                    PathBuf::from(fallback_name),
                    Some(format!(
                        "{} default path error: {}. Using local '{}'.",
                        label, err, fallback_name
                    )),
                ),
            },
        }
    }

    fn project_categories(records: &[CategoryRecord]) -> Vec<CategoryInfo> {
        records
            .iter()
            .map(CategoryRecord::to_category_info)
            .collect()
    }

    fn resolve_default_database_path(data_file_path: &Path) -> (PathBuf, Option<String>) {
        let default_path = Self::default_database_path_for_data_path(data_file_path);

        if let Some(parent) = default_path.parent()
            && let Err(err) = create_dir_all(parent)
        {
            return (
                PathBuf::from("budget.db"),
                Some(format!(
                    "Database default path error: Could not create parent dir for {}: {}. Using local 'budget.db'.",
                    default_path.display(),
                    err
                )),
            );
        }

        (default_path, None)
    }

    fn category_store_for_path(database_path: &Path) -> SqliteCategoryStore {
        SqliteCategoryStore::new(SqliteDatabase::new(database_path))
    }

    pub(crate) fn category_store(&self) -> SqliteCategoryStore {
        Self::category_store_for_path(&self.database_path)
    }

    fn transaction_store_for_path(database_path: &Path) -> SqliteTransactionStore {
        SqliteTransactionStore::new(SqliteDatabase::new(database_path))
    }

    pub(crate) fn transaction_store(&self) -> SqliteTransactionStore {
        Self::transaction_store_for_path(&self.database_path)
    }

    /// Reload the working transaction set from the database and re-derive the in-memory
    /// generated recurring occurrences. Call after any mutation that touched the store.
    pub(crate) fn reload_transactions_from_db(&mut self) -> Result<(), Error> {
        self.transactions = self.transaction_store().list()?;
        // Re-derives generated occurrences and recomputes sort/filter/summaries.
        self.generate_recurring_transactions();
        Ok(())
    }

    /// One-time, non-destructive migration of the legacy transactions CSV into the database.
    /// Gated by a metadata flag so it runs at most once. Returns an optional status message.
    fn run_one_time_csv_migration(
        database_path: &Path,
        data_file_path: &Path,
    ) -> Result<Option<String>, Error> {
        let database = SqliteDatabase::new(database_path);
        let mut conn = database.open_connection("transaction migration")?;
        database.run_migrations(&mut conn)?;

        if database
            .metadata_value(&conn, "transactions_migrated")?
            .is_some()
        {
            return Ok(None);
        }

        let mut status = None;
        if data_file_path.exists() {
            // Only real rows are imported; generated occurrences are re-derived from sources.
            let real_rows: Vec<Transaction> = load_transactions(data_file_path)?
                .into_iter()
                .filter(|tx| !tx.is_generated_from_recurring)
                .collect();

            if !real_rows.is_empty() {
                let store = SqliteTransactionStore::new(database.clone());
                let summary = store.import_merge(&real_rows)?;

                // Preserve the original file (never delete) by renaming it aside.
                let backup = {
                    let mut name = data_file_path.to_path_buf().into_os_string();
                    name.push(".migrated-backup");
                    PathBuf::from(name)
                };
                let backup_note = match std::fs::rename(data_file_path, &backup) {
                    Ok(_) => format!(" Original CSV saved as {}.", backup.display()),
                    Err(_) => String::new(),
                };
                status = Some(format!(
                    "Migrated {} transactions from CSV to the database.{}",
                    summary.added, backup_note
                ));
            }
        }

        database.set_metadata_value(&conn, "transactions_migrated", "1")?;
        Ok(status)
    }

    pub(crate) fn initialize_category_database(
        database_path: &Path,
        seed_categories: &[CategoryInfo],
    ) -> Result<(), Error> {
        let store = Self::category_store_for_path(database_path);
        store.initialize(seed_categories)?;
        Ok(())
    }

    pub(crate) fn prepare_category_database_for_path_change(
        current_database_path: &Path,
        new_database_path: &Path,
        seed_categories: &[CategoryInfo],
    ) -> Result<(), Error> {
        if current_database_path != new_database_path
            && !new_database_path.exists()
            && current_database_path.exists()
        {
            let destination_database = SqliteDatabase::new(new_database_path);
            destination_database.ensure_parent_dir()?;
            copy(current_database_path, new_database_path).map_err(|err| {
                Error::other(format!(
                    "Failed to copy database from '{}' to '{}': {}",
                    current_database_path.display(),
                    new_database_path.display(),
                    err
                ))
            })?;
        }

        Self::initialize_category_database(new_database_path, seed_categories)
    }

    fn load_category_records(
        database_path: &Path,
        seed_categories: &[CategoryInfo],
    ) -> Result<Vec<CategoryRecord>, Error> {
        let store = Self::category_store_for_path(database_path);
        store.initialize(seed_categories)?;
        store.list()
    }

    pub(crate) fn refresh_category_state(&mut self, records: Vec<CategoryRecord>) {
        self.category_records = records;
        self.categories = Self::project_categories(&self.category_records);
        self.apply_category_filter();
    }

    pub(crate) fn refresh_categories_from_database(&mut self) -> Result<(), Error> {
        let store = self.category_store();
        let records = store.list()?;
        self.refresh_category_state(records);
        Ok(())
    }

    pub(crate) fn reload_categories_from_store(&mut self) -> Result<(), Error> {
        self.refresh_categories_from_database()
    }

    pub fn quit(&mut self) {
        self.should_quit = true;
    }
    pub fn next_item(&mut self) {
        let list_len = match self.mode {
            AppMode::Normal | AppMode::Filtering => self.filtered_indices.len(),
            AppMode::Summary => 12,
            AppMode::CategorySummary => self.cached_visible_category_items.len(),
            AppMode::Budget => 12,
            _ => 0,
        };
        if list_len == 0 {
            return;
        }
        let current_selection = self.table_state.selected().unwrap_or(0);
        let next_selection = if current_selection >= list_len - 1 {
            0
        } else {
            current_selection + 1
        };
        self.table_state.select(Some(next_selection));
    }
    pub fn previous_item(&mut self) {
        let list_len = match self.mode {
            AppMode::Normal | AppMode::Filtering => self.filtered_indices.len(),
            AppMode::Summary => 12,
            AppMode::CategorySummary => self.cached_visible_category_items.len(),
            AppMode::Budget => 12,
            _ => 0,
        };
        if list_len == 0 {
            return;
        }
        let current_selection = self.table_state.selected().unwrap_or(0);
        let prev_selection = if current_selection == 0 {
            list_len - 1
        } else {
            current_selection - 1
        };
        self.table_state.select(Some(prev_selection));
    }
    pub fn decrement_date(&mut self) {
        self.adjust_date(-1, DateUnit::Day);
    }
    pub fn increment_date(&mut self) {
        self.adjust_date(1, DateUnit::Day);
    }
    pub fn decrement_month(&mut self) {
        self.adjust_date(-1, DateUnit::Month);
    }
    pub fn increment_month(&mut self) {
        self.adjust_date(1, DateUnit::Month);
    }

    /// Jump to the very first item in the transaction list
    /// Only works in Normal and Filtering modes
    pub fn jump_to_first(&mut self) {
        match self.mode {
            AppMode::Normal | AppMode::Filtering => {
                let list_len = self.filtered_indices.len();
                if list_len > 0 {
                    self.table_state.select(Some(0));
                }
            }
            _ => {}
        }
    }

    /// Jump to the very last item in the transaction list
    /// Only works in Normal and Filtering modes
    pub fn jump_to_last(&mut self) {
        match self.mode {
            AppMode::Normal | AppMode::Filtering => {
                let list_len = self.filtered_indices.len();
                if list_len > 0 {
                    let last_index = list_len - 1;
                    self.table_state.select(Some(last_index));
                }
            }
            _ => {}
        }
    }

    /// Page size for transaction navigation (PageUp/PageDown)
    const TRANSACTION_PAGE_SIZE: usize = 20;

    /// Jump up by approximately one page worth of transactions
    /// Only works in Normal and Filtering modes
    pub fn page_up(&mut self) {
        match self.mode {
            AppMode::Normal | AppMode::Filtering => {
                let list_len = self.filtered_indices.len();
                if list_len == 0 {
                    return;
                }

                let page_size = Self::TRANSACTION_PAGE_SIZE;
                let current_selection = self.table_state.selected().unwrap_or(0);
                let new_selection = current_selection.saturating_sub(page_size);

                self.table_state.select(Some(new_selection));
            }
            _ => {}
        }
    }

    /// Jump down by approximately one page worth of transactions
    /// Only works in Normal and Filtering modes
    pub fn page_down(&mut self) {
        match self.mode {
            AppMode::Normal | AppMode::Filtering => {
                let list_len = self.filtered_indices.len();
                if list_len == 0 {
                    return;
                }

                let page_size = Self::TRANSACTION_PAGE_SIZE;
                let current_selection = self.table_state.selected().unwrap_or(0);
                let new_selection = (current_selection + page_size).min(list_len - 1);

                self.table_state.select(Some(new_selection));
            }
            _ => {}
        }
    }
    pub(crate) fn get_original_index(&self, filtered_view_index: usize) -> Option<usize> {
        self.filtered_indices.get(filtered_view_index).copied()
    }
    pub(crate) fn sort_transactions(&mut self) {
        crate::app::util::sort_transactions_impl(
            &mut self.transactions,
            self.sort_by,
            self.sort_order,
        );
    }
    pub(crate) fn calculate_monthly_summaries(&mut self) {
        self.monthly_summaries.clear();
        let mut years = Vec::new();
        for &idx in &self.filtered_indices {
            if let Some(tx) = self.transactions.get(idx) {
                let year = tx.date.year();
                let month = tx.date.month();
                let summary = self.monthly_summaries.entry((year, month)).or_default();
                match tx.transaction_type {
                    TransactionType::Income => summary.income += tx.amount,
                    TransactionType::Expense => summary.expense += tx.amount,
                }
                if !years.contains(&year) {
                    years.push(year);
                }
            }
        }
        years.sort_unstable();
        self.summary_years = years;
        if !self.summary_years.is_empty() {
            self.selected_summary_year_index = self
                .selected_summary_year_index
                .min(self.summary_years.len() - 1);
        } else {
            self.selected_summary_year_index = 0;
        }
        self.refresh_budget_years();
    }
    pub(crate) fn calculate_category_summaries(&mut self) {
        self.category_summaries.clear();
        let mut years = HashSet::new();
        for tx in self
            .filtered_indices
            .iter()
            .map(|&idx| &self.transactions[idx])
        {
            let year = tx.date.year();
            let month = tx.date.month();
            years.insert(year);
            let category_key = tx.category.trim();
            let subcategory_key = tx.subcategory.trim();
            let final_category = if category_key.is_empty() {
                "Uncategorized"
            } else {
                category_key
            };
            let month_map = self.category_summaries.entry((year, month)).or_default();
            let summary = month_map
                .entry((final_category.to_string(), subcategory_key.to_string()))
                .or_default();
            match tx.transaction_type {
                TransactionType::Income => summary.income += tx.amount,
                TransactionType::Expense => summary.expense += tx.amount,
            }
        }
        self.category_summary_years = years.into_iter().collect();
        self.category_summary_years.sort_unstable();
        if !self.category_summary_years.is_empty() {
            self.category_summary_year_index = self
                .category_summary_year_index
                .min(self.category_summary_years.len() - 1);
        } else {
            self.category_summary_year_index = 0;
        }
        let list_len = self.cached_visible_category_items.len();
        if list_len == 0 {
            self.category_summary_table_state.select(None);
        } else {
            let current_selection = self.category_summary_table_state.selected().unwrap_or(0);
            let new_selection = current_selection.min(list_len - 1);
            self.category_summary_table_state
                .select(Some(new_selection));
        }
    }
    pub(crate) fn adjust_date(&mut self, amount: i64, unit: DateUnit) {
        if self.current_add_edit_field == 0 {
            if let Ok(current_date) =
                NaiveDate::parse_from_str(&self.add_edit_fields[0], crate::model::DATE_FORMAT)
            {
                let new_date = match unit {
                    DateUnit::Day => {
                        if amount > 0 {
                            current_date + Duration::days(amount)
                        } else {
                            current_date - Duration::days(-amount)
                        }
                    }
                    DateUnit::Month => {
                        // Use centralized month arithmetic
                        crate::validation::add_months(current_date, amount as i32)
                    }
                };
                self.add_edit_fields[0] = new_date.format(crate::model::DATE_FORMAT).to_string();
                self.add_edit_cursor = self.add_edit_fields[0].len();
                self.clear_status_message() // Clear status on successful adjustment
            } else {
                self.set_status_message(
                    format!(
                        "Error: Could not parse date '{}'. Use YYYY-MM-DD format.",
                        self.add_edit_fields[0]
                    ),
                    None,
                );
            }
        }
    }
    pub fn get_default_data_file_path() -> Result<PathBuf, Error> {
        const DATA_FILE_NAME: &str = "transactions.csv";
        const APP_DATA_SUBDIR: &str = "BudgetTracker";
        match dirs::data_dir() {
            Some(mut path) => {
                path.push(APP_DATA_SUBDIR);
                create_dir_all(&path)?;
                path.push(DATA_FILE_NAME);
                Ok(path)
            }
            None => Err(Error::new(
                ErrorKind::NotFound,
                "Could not find user data directory",
            )),
        }
    }

    pub fn default_database_path_for_data_path(data_file_path: &Path) -> PathBuf {
        const DATABASE_FILE_NAME: &str = "budget.db";

        match data_file_path.parent() {
            Some(parent) => parent.join(DATABASE_FILE_NAME),
            None => PathBuf::from(DATABASE_FILE_NAME),
        }
    }

    pub fn get_default_database_file_path() -> Result<PathBuf, Error> {
        Self::get_default_data_file_path()
            .map(|data_path| Self::default_database_path_for_data_path(&data_path))
    }
    // --- Sorting Logic ---
    pub(crate) fn set_sort_column(&mut self, column: SortColumn) {
        if self.sort_by == column {
            self.sort_order = match self.sort_order {
                SortOrder::Ascending => SortOrder::Descending,
                SortOrder::Descending => SortOrder::Ascending,
            };
        } else {
            self.sort_by = column;
            self.sort_order = SortOrder::Ascending;
        }

        // Preserve the current filter type when sorting
        // Check if any advanced filter fields are active
        let has_advanced_filters = self
            .advanced_filter_fields
            .iter()
            .any(|field| !field.is_empty());

        if has_advanced_filters {
            self.apply_advanced_filter();
        } else {
            self.apply_filter();
        }
    }

    pub fn set_status_message<S: Into<String>>(&mut self, message: S, duration: Option<Duration>) {
        self.status_message = Some(message.into());
        self.status_expiry = duration.map(|d| {
            std::time::Instant::now() + std::time::Duration::from_secs(d.num_seconds() as u64)
        });
    }

    pub fn clear_status_message(&mut self) {
        self.status_message = None;
        self.status_expiry = None;
    }
}