//
//  AddSearchEngineViewController.swift
//  App
//
//  Created by James Magahern on 9/29/25.
//

import SwiftUI
import UIKit

@MainActor
struct AddSearchEngineView: View
{
    @State var model: ViewModel

    var body: some View {
        Form {
            Section {
                HStack {
                    Text("Name")
                    TextField("Name", text: $model.name)
                        .multilineTextAlignment(.trailing)
                        .autocorrectionDisabled()
                }
            }

            Section {
                HStack {
                    Text("URL")
                    TextField("https://example.com/query=%q", text: $model.url)
                        .multilineTextAlignment(.trailing)
                        .autocorrectionDisabled()
                        .textContentType(.none)
                }
            } footer: {
                Text("URL must contain %q, which will be replaced by the query. ")
            }

            Section {
                Toggle("Set as default", isOn: $model.makeDefault)
            }
        }
        .navigationTitle("Add Search Engine")
    }

    @MainActor
    @Observable
    class ViewModel
    {
        var name: String = ""
        var url: String = ""
        var makeDefault: Bool = false
    }
}

@MainActor
class AddSearchEngineViewController: UIHostingController<AddSearchEngineView>
{
    public var viewModel: AddSearchEngineView.ViewModel

    init() {
        self.viewModel = AddSearchEngineView.ViewModel()
        super.init(rootView: AddSearchEngineView(model: viewModel))
    }
    
    @MainActor @preconcurrency required dynamic init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

#Preview {
    @Previewable @State var model = AddSearchEngineView.ViewModel()
    AddSearchEngineView(model: model)
}
