import SwiftUI
import Models

struct AccountSetupView: View {
	@Bindable var viewModel: AccountSetupViewModel
	var onComplete: () -> Void

	var body: some View {
		Form {
			Section("Account") {
				TextField("Email", text: $viewModel.email)
					.onChange(of: viewModel.email) { _, newValue in
						if newValue.contains("@") && !viewModel.isManualMode {
							Task { await viewModel.autoDiscover() }
						}
					}
					#if os(iOS)
					.textContentType(.emailAddress)
					.keyboardType(.emailAddress)
					.autocapitalization(.none)
					#endif
				SecureField("Password", text: $viewModel.password)
				TextField("Account Name (optional)", text: $viewModel.accountName)
			}

			if viewModel.isManualMode || viewModel.autoDiscoveryFailed {
				Section("IMAP") {
					TextField("IMAP Host", text: $viewModel.imapHost)
					TextField("IMAP Port", text: $viewModel.imapPort)
				}

				Section("SMTP") {
					TextField("SMTP Host", text: $viewModel.smtpHost)
					TextField("SMTP Port", text: $viewModel.smtpPort)
					Picker("Security", selection: $viewModel.smtpSecurity) {
						Text("STARTTLS").tag(SMTPSecurity.starttls)
						Text("SSL/TLS").tag(SMTPSecurity.ssl)
					}
				}
			}

			if let error = viewModel.errorMessage {
				Section {
					Text(error)
						.foregroundStyle(.red)
				}
			}

			Section {
				if viewModel.isAutoDiscovering {
					ProgressView("Discovering settings…")
				} else {
					Button("Connect") {
						onComplete()
					}
					.disabled(!viewModel.canSubmit)

					if !viewModel.isManualMode {
						Button("Enter server settings manually") {
							viewModel.isManualMode = true
						}
					}
				}
			}
		}
		.formStyle(.grouped)
		.navigationTitle("Add Account")
		.task {
			if !viewModel.email.isEmpty && !viewModel.isManualMode {
				await viewModel.autoDiscover()
			}
		}
	}
}
