import SwiftUI
import Models

struct ThreadListView: View {
	@Bindable var viewModel: MailViewModel

	var body: some View {
		List(viewModel.threads, selection: Binding(
			get: { viewModel.selectedThread?.id },
			set: { newId in
				if let thread = viewModel.threads.first(where: { $0.id == newId }) {
					viewModel.selectThread(thread)
				}
			}
		)) { thread in
			ThreadRow(thread: thread)
				.tag(thread.id)
		}
		.listStyle(.inset)
		.navigationTitle(viewModel.selectedMailbox?.name ?? "Mail")
		.overlay {
			if viewModel.threads.isEmpty {
				ContentUnavailableView(
					"No Messages",
					systemImage: "tray",
					description: Text("No threads in this mailbox")
				)
			}
		}
	}
}

struct ThreadRow: View {
	let thread: ThreadSummary

	var body: some View {
		VStack(alignment: .leading, spacing: 4) {
			HStack {
				Text(thread.senders)
					.fontWeight(thread.unreadCount > 0 ? .bold : .regular)
					.lineLimit(1)
				Spacer()
				Text(thread.lastDate, style: .relative)
					.font(.caption)
					.foregroundStyle(.secondary)
			}
			Text(thread.subject ?? "(No Subject)")
				.font(.subheadline)
				.lineLimit(1)
			if let snippet = thread.snippet {
				Text(snippet)
					.font(.caption)
					.foregroundStyle(.tertiary)
					.lineLimit(1)
			}
			HStack(spacing: 8) {
				if thread.messageCount > 1 {
					Text("\(thread.messageCount)")
						.font(.caption2)
						.foregroundStyle(.secondary)
						.padding(.horizontal, 6)
						.padding(.vertical, 1)
						.background(.quaternary, in: Capsule())
				}
				if thread.unreadCount > 0 {
					Circle()
						.fill(.blue)
						.frame(width: 8, height: 8)
				}
			}
		}
		.padding(.vertical, 2)
	}
}
