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
package main

import (
	"database/sql"
	"fmt"
	"log"
	"time"

	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
)

// ArchivedViewModel manages the archived clients view
type ArchivedViewModel struct {
	clients        []Client
	selectedClient int
	viewportStart  int
	pageSize       int
	db             *sql.DB
	windowWidth    int
	windowHeight   int
}

// NewArchivedViewModel creates a new archived view and loads archived clients from the database
func NewArchivedViewModel(db *sql.DB, windowWidth, windowHeight int) (*ArchivedViewModel, error) {
	clients, err := LoadArchivedClients(db)
	if err != nil {
		return nil, fmt.Errorf("failed to load archived clients: %w", err)
	}

	// Calculate page size (same logic as main view)
	pageSize := clampMin(windowHeight-9, 1)

	return &ArchivedViewModel{
		clients:        clients,
		selectedClient: 0,
		viewportStart:  0,
		pageSize:       pageSize,
		db:             db,
		windowWidth:    windowWidth,
		windowHeight:   windowHeight,
	}, nil
}

// Update handles messages for the archived view
// Returns (updatedView, cmd, shouldExit)
// If shouldExit is true, the caller should exit back to normal view
func (a *ArchivedViewModel) Update(msg tea.Msg) (*ArchivedViewModel, tea.Cmd, bool) {
	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		a.windowWidth = msg.Width
		a.windowHeight = msg.Height
		a.pageSize = clampMin(msg.Height-9, 1)
		return a, nil, false

	case tea.KeyMsg:
		keyStr := msg.String()

		// Handle quit commands
		if keyStr == "q" || keyStr == "ctrl+c" {
			return a, tea.Quit, false
		}

		// Handle exit to normal view
		if keyStr == "ctrl+u" {
			return a, nil, true
		}

		// Handle navigation and actions
		shouldExit := a.handleKeyPress(keyStr)
		return a, nil, shouldExit
	}

	return a, nil, false
}

// handleKeyPress processes keyboard input
// Returns true if should exit to normal view
func (a *ArchivedViewModel) handleKeyPress(keyStr string) bool {
	// Check if we have any clients
	if len(a.clients) == 0 {
		return false
	}

	switch keyStr {
	case "ctrl+a":
		// Unarchive selected client
		if err := a.unarchiveSelected(); err != nil {
			log.Printf("Error unarchiving client: %v", err)
			return false
		}

		// Reload archived clients
		newClients, err := LoadArchivedClients(a.db)
		if err != nil {
			log.Printf("Error reloading archived clients: %v", err)
			return false
		}
		a.clients = newClients

		// Adjust selection if needed
		if len(a.clients) == 0 {
			// No more archived clients, stay in view showing empty message
			a.selectedClient = 0
			a.viewportStart = 0
		} else {
			a.selectedClient = clampIndex(a.selectedClient, len(a.clients))
			a.adjustViewport()
		}

	case "up", "k":
		a.selectedClient = saturatingDec(a.selectedClient, 0)
		a.adjustViewport()

	case "down", "j":
		a.selectedClient = saturatingInc(a.selectedClient, len(a.clients)-1)
		a.adjustViewport()

	case "pgup":
		a.selectedClient = saturatingSub(a.selectedClient, a.pageSize, 0)
		a.adjustViewport()

	case "pgdown":
		a.selectedClient = saturatingAdd(a.selectedClient, a.pageSize, len(a.clients)-1)
		a.adjustViewport()

	case "home", "g":
		a.selectedClient = 0
		a.adjustViewport()

	case "end", "G":
		a.selectedClient = len(a.clients) - 1
		a.adjustViewport()
	}

	return false
}

// unarchiveSelected unarchives the currently selected client
func (a *ArchivedViewModel) unarchiveSelected() error {
	if len(a.clients) == 0 {
		return fmt.Errorf("no clients to unarchive")
	}

	client := a.clients[a.selectedClient]
	if err := ArchiveClient(a.db, client.ID); err != nil {
		return fmt.Errorf("failed to unarchive client: %w", err)
	}

	log.Printf("Unarchived client: %s", client.Name)
	return nil
}

// adjustViewport ensures the selected client is visible in the viewport
func (a *ArchivedViewModel) adjustViewport() {
	if a.selectedClient < a.viewportStart {
		a.viewportStart = a.selectedClient
	}
	if a.selectedClient >= a.viewportStart+a.pageSize {
		a.viewportStart = a.selectedClient - a.pageSize + 1
	}
}

// View renders the archived clients view
func (a *ArchivedViewModel) View() string {
	var output string

	// Title
	titleStyle := lipgloss.NewStyle().
		Bold(true).
		Foreground(ColorTitleText).
		Padding(0, 1)
	output += titleStyle.Render("ARCHIVED CLIENTS (Ctrl+u to return, Ctrl+a to unarchive)") + "\n\n"

	if len(a.clients) == 0 {
		emptyStyle := lipgloss.NewStyle().
			Foreground(ColorTextDim).
			Padding(2, 4)
		output += emptyStyle.Render("No archived clients")
		return output
	}

	// Define border style for the table
	borderStyle := lipgloss.NewStyle().
		Border(lipgloss.RoundedBorder()).
		BorderForeground(ColorTableBorder)

	// Define table columns for archived clients
	columns := []TableColumn{
		{
			Name:  "Client Name",
			Width: 30,
			Align: lipgloss.Left,
			RenderCell: func(data any, width int) string {
				client := data.(Client)
				nameStyle := lipgloss.NewStyle().Foreground(ColorAgeNewest)
				return renderCell(nameStyle.Render(client.Name), width, lipgloss.NewStyle())
			},
		},
		{
			Name:  "Archived At",
			Width: 20,
			Align: lipgloss.Left,
			RenderCell: func(data any, width int) string {
				client := data.(Client)
				if !client.ArchivedAt.Valid {
					return renderCell("(no timestamp)", width, lipgloss.NewStyle().Foreground(ColorTextDim))
				}
				// Format as "YYYY-MM-DD HH:MM"
				t := time.Unix(client.ArchivedAt.Int64, 0)
				formatted := t.Format("2006-01-02 15:04")
				timeStyle := lipgloss.NewStyle().Foreground(ColorAgeMid)
				return renderCell(formatted, width, timeStyle)
			},
		},
		{
			Name:  "Total Hours",
			Width: 12,
			Align: lipgloss.Right,
			RenderCell: func(data any, width int) string {
				client := data.(Client)
				entries := filterEntries(client.DisplayItems)
				totalHours := calculateTotalHours(entries)
				hoursStyle := lipgloss.NewStyle().Foreground(ColorTextDim).Align(lipgloss.Right)
				return renderCell(fmt.Sprintf("%.1fh", totalHours), width, hoursStyle)
			},
		},
	}

	// Create table
	table := NewTable(columns, a.windowWidth, borderStyle)

	// Render header
	header := table.RenderHeader()
	output += header + "\n"

	// Render visible rows (clients as rows instead of time entries)
	visibleEnd := min(a.viewportStart+a.pageSize, len(a.clients))

	selectionBgColor := ColorSelectionBackground

	for i := a.viewportStart; i < visibleEnd; i++ {
		client := a.clients[i]
		var row string
		if i == a.selectedClient {
			row = table.RenderRowWithBackground(client, selectionBgColor)
		} else {
			row = table.RenderRow(client)
		}
		output += row + "\n"
	}

	// Add empty lines if viewport isn't full
	for i := visibleEnd; i < a.viewportStart+a.pageSize; i++ {
		output += "\n"
	}

	// Apply border to entire view
	finalView := borderStyle.Render(output)

	return finalView
}