summaryrefslogtreecommitdiff
path: root/src/tui/ui.rs
blob: ceb66b4a20b7a94867900f1586532f36cc5a2ee8 (plain)
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
use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph, Tabs},
    Frame,
};
use crate::tui::app::{App, View};
use crate::tui::{dashboard, transactions};

pub fn draw(f: &mut Frame, app: &mut App) {
    let size = f.size();
    
    // Create main layout
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // Header
            Constraint::Min(0),    // Content
            Constraint::Length(3), // Footer
        ])
        .split(size);
    
    draw_header(f, app, chunks[0]);
    
    // Draw content based on current view
    match app.current_view {
        View::Dashboard => dashboard::draw_dashboard(f, app, chunks[1]),
        View::Transactions => transactions::draw_transactions(f, app, chunks[1]),
        View::Budgets => draw_budgets(f, app, chunks[1]),
        View::Investments => draw_investments(f, app, chunks[1]),
    }
    
    draw_footer(f, app, chunks[2]);
    
    // Draw help overlay if needed
    if app.show_help {
        draw_help(f, size);
    }
}

fn draw_header(f: &mut Frame, app: &App, area: Rect) {
    let titles = vec!["Dashboard", "Transactions", "Budgets", "Investments"];
    let selected = match app.current_view {
        View::Dashboard => 0,
        View::Transactions => 1,
        View::Budgets => 2,
        View::Investments => 3,
    };
    
    let header = Tabs::new(titles)
        .block(Block::default()
            .title(" 🌿 Spendr - Personal Finance ")
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::Green)))
        .select(selected)
        .style(Style::default().fg(Color::Gray))
        .highlight_style(Style::default()
            .fg(Color::Green)
            .add_modifier(Modifier::BOLD));
    
    f.render_widget(header, area);
}

fn draw_footer(f: &mut Frame, app: &App, area: Rect) {
    let shortcuts = match app.current_view {
        View::Dashboard => vec![
            ("Tab", "Next View"),
            ("r", "Refresh"),
            ("?", "Help"),
            ("q", "Quit"),
        ],
        View::Transactions => vec![
            ("j/k ↑↓", "Navigate"),
            ("/", "Search"),
            ("c", "Categorize"),
            ("Tab", "Next View"),
            ("q", "Quit"),
        ],
        View::Budgets => vec![
            ("↑↓", "Navigate"),
            ("e", "Edit Budget"),
            ("Tab", "Next View"),
            ("q", "Quit"),
        ],
        View::Investments => vec![
            ("p", "Performance"),
            ("r", "Rebalance"),
            ("Tab", "Next View"),
            ("q", "Quit"),
        ],
    };
    
    let shortcut_text: Vec<Span> = shortcuts
        .iter()
        .flat_map(|(key, desc)| {
            vec![
                Span::styled(
                    format!(" [{}] ", key),
                    Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD),
                ),
                Span::raw(format!("{} ", desc)),
            ]
        })
        .collect();
    
    let footer = Paragraph::new(Line::from(shortcut_text))
        .block(Block::default()
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::DarkGray)))
        .alignment(Alignment::Center);
    
    f.render_widget(footer, area);
}

fn draw_budgets(f: &mut Frame, app: &App, area: Rect) {
    let budgets_text: Vec<Line> = app.budgets.iter()
        .map(|(category, budget, spent, _remaining)| {
            let percentage = if *budget > 0.0 { spent / budget } else { 0.0 };
            let bar_width = 20;
            let filled = (percentage * bar_width as f64) as usize;
            let bar = format!("{}{}", "█".repeat(filled.min(bar_width)), "░".repeat(bar_width.saturating_sub(filled)));
            
            let status_color = if percentage > 1.0 {
                Color::Red
            } else if percentage > 0.8 {
                Color::Yellow
            } else {
                Color::Green
            };
            
            Line::from(vec![
                Span::raw(format!("{:<15} ", category)),
                Span::styled(bar, Style::default().fg(status_color)),
                Span::raw(format!(" ${:.0}/${:.0}", spent.max(0.0), budget.max(0.0))),
            ])
        })
        .collect();
    
    let budgets = Paragraph::new(budgets_text)
        .block(Block::default()
            .title(" 🎯 Budget Status ")
            .borders(Borders::ALL));
    
    f.render_widget(budgets, area);
}

fn draw_investments(f: &mut Frame, app: &App, area: Rect) {
    let total_value: f64 = app.portfolios.iter().map(|p| p.total_market_value).sum();
    let total_book: f64 = app.portfolios.iter().map(|p| p.total_book_value).sum();
    let total_gain = total_value - total_book;
    let gain_pct = if total_book > 0.0 { (total_gain / total_book) * 100.0 } else { 0.0 };
    
    let investment_text = vec![
        Line::from(format!("Total Market Value: ${:.2}", if total_value.is_finite() { total_value } else { 0.0 })),
        Line::from(format!("Total Book Value:   ${:.2}", if total_book.is_finite() { total_book } else { 0.0 })),
        Line::from(vec![
            Span::raw("Unrealized Gain:    "),
            Span::styled(
                format!("${:.2} ({:+.1}%)", 
                    if total_gain.is_finite() { total_gain } else { 0.0 }, 
                    if gain_pct.is_finite() { gain_pct } else { 0.0 }
                ),
                Style::default().fg(if total_gain >= 0.0 { Color::Green } else { Color::Red }),
            ),
        ]),
        Line::from(""),
        Line::from("Portfolios:"),
    ];
    
    let mut portfolio_lines = investment_text;
    for portfolio in &app.portfolios {
        portfolio_lines.push(Line::from(format!(
            "  {} ({:?}): ${:.2}",
            portfolio.account_id,
            portfolio.account_type,
            if portfolio.total_market_value.is_finite() { portfolio.total_market_value } else { 0.0 }
        )));
    }
    
    let investments = Paragraph::new(portfolio_lines)
        .block(Block::default()
            .title(" 📈 Investment Overview ")
            .borders(Borders::ALL));
    
    f.render_widget(investments, area);
}

fn draw_help(f: &mut Frame, area: Rect) {
    let help_text = vec![
        Line::from(""),
        Line::from(vec![Span::styled(" Spendr TUI Help ", Style::default().add_modifier(Modifier::BOLD))]),
        Line::from(""),
        Line::from(" Navigation:"),
        Line::from("   Tab/Shift+Tab - Switch between views"),
        Line::from("   ↑/↓ or j/k - Navigate lists (vim bindings)"),
        Line::from("   Enter - Select/Edit"),
        Line::from(""),
        Line::from(" View Shortcuts:"),
        Line::from("   d - Dashboard"),
        Line::from("   t - Transactions"),
        Line::from("   b - Budgets"),
        Line::from("   i - Investments"),
        Line::from(""),
        Line::from(" General:"),
        Line::from("   / - Search"),
        Line::from("   r - Refresh data"),
        Line::from("   ? - Toggle this help"),
        Line::from("   q - Quit"),
        Line::from(""),
        Line::from(" Press any key to close this help"),
    ];
    
    let help_width = 50;
    let help_height = 22;
    let help_area = centered_rect(help_width, help_height, area);
    
    let help = Paragraph::new(help_text)
        .block(Block::default()
            .title(" Help ")
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::Yellow)))
        .style(Style::default().bg(Color::Black))
        .alignment(Alignment::Left);
    
    f.render_widget(help, help_area);
}

fn centered_rect(width: u16, height: u16, area: Rect) -> Rect {
    let popup_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length((area.height.saturating_sub(height)) / 2),
            Constraint::Length(height),
            Constraint::Length((area.height.saturating_sub(height)) / 2),
        ])
        .split(area);

    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Length((area.width.saturating_sub(width)) / 2),
            Constraint::Length(width),
            Constraint::Length((area.width.saturating_sub(width)) / 2),
        ])
        .split(popup_layout[1])[1]
}