import SwiftUI
import Models
import MailStore

struct ContentView: View {
	@State private var viewModel = MailViewModel()
	@State private var accountSetup = AccountSetupViewModel()
	@State private var showingAccountSetup = false

	var body: some View {
		Group {
			if viewModel.hasAccount {
				mailView
			} else {
				NavigationStack {
					AccountSetupView(viewModel: accountSetup) {
						connectAccount()
					}
				}
			}
		}
		.onAppear {
			loadExistingAccount()
		}
	}

	private var mailView: some View {
		NavigationSplitView {
			SidebarView(viewModel: viewModel)
		} content: {
			ThreadListView(viewModel: viewModel)
		} detail: {
			ThreadDetailView(
				thread: viewModel.selectedThread,
				messages: viewModel.messages
			)
		}
		.safeAreaInset(edge: .bottom) {
			statusBanner
		}
		.task {
			await viewModel.syncNow()
			viewModel.startPeriodicSync()
		}
	}

	@ViewBuilder
	private var statusBanner: some View {
		switch viewModel.syncState {
		case .error(let message):
			HStack {
				Image(systemName: "wifi.slash")
				Text("Offline — showing cached mail")
				Spacer()
				Button("Retry") {
					Task { await viewModel.syncNow() }
				}
				.buttonStyle(.borderless)
			}
			.font(.caption)
			.padding(8)
			.background(.yellow.opacity(0.2))
		case .syncing(let mailbox):
			HStack {
				ProgressView()
					.controlSize(.small)
				Text("Syncing\(mailbox.map { " \($0)" } ?? "")…")
					.font(.caption)
				Spacer()
			}
			.padding(8)
			.background(.blue.opacity(0.1))
		case .idle:
			EmptyView()
		}
	}

	private func connectAccount() {
		guard let (config, credentials) = accountSetup.buildConfig() else { return }
		do {
			try viewModel.setup(config: config, credentials: credentials)
			try KeychainService.saveCredentials(credentials, for: config.id)
			if let data = try? JSONEncoder().encode(config) {
				UserDefaults.standard.set(data, forKey: "accountConfig")
			}
			Task {
				await viewModel.syncNow()
				await viewModel.loadMailboxes(accountId: config.id)
				viewModel.startObservingThreads(accountId: config.id)
				viewModel.startPeriodicSync()
			}
		} catch {
			accountSetup.errorMessage = error.localizedDescription
		}
	}

	private func loadExistingAccount() {
		guard let data = UserDefaults.standard.data(forKey: "accountConfig"),
			  let config = try? JSONDecoder().decode(AccountConfig.self, from: data),
			  let credentials = try? KeychainService.loadCredentials(for: config.id)
		else { return }
		do {
			try viewModel.setup(config: config, credentials: credentials)
			Task {
				await viewModel.loadMailboxes(accountId: config.id)
				viewModel.startObservingThreads(accountId: config.id)
				await viewModel.syncNow()
				viewModel.startPeriodicSync()
			}
		} catch {
			// Account config exists but setup failed — show account setup
		}
	}
}
