import SwiftUI
@preconcurrency import Translation

struct ContentView: View {
   @State private var appData = ApplicationData.shared
   @State private var textInput: String = ""

   var body: some View {
      VStack {
         HStack {
            TextField("Insert Text", text: $textInput)
               .textFieldStyle(.roundedBorder)
            Button("Translate") {
               let text = textInput.trimmingCharacters(in: .whitespacesAndNewlines)
               if !text.isEmpty {
                  appData.updateConfiguration()
               }
            }
            .buttonStyle(.borderedProminent)
         }
         HStack {
            Spacer()
            Picker("From", selection: $appData.selectedSource) {
               ForEach(appData.listLanguages.indices, id: \.self) { index in
                  let name = appData.getLanguageName(index: index)
                  Text(name)
                     .tag(index)
               }
            }.frame(minWidth: 0, maxWidth: .infinity)

            Text("<->")

            Picker("To", selection: $appData.selectedTarget) {
               ForEach(appData.listLanguages.indices, id: \.self) { index in
                  let name = appData.getLanguageName(index: index)
                  Text(name)
                     .tag(index)
               }
            }.frame(minWidth: 0, maxWidth: .infinity)
            Spacer()
         }.padding(.top, 15)
         Spacer()
      }
      .padding()
      .onChange(of: appData.selectedSource) { old, new in
         appData.changeTarget(old: old, new: new)
      }
      .onChange(of: appData.selectedTarget) { old, new in
         appData.changeSource(old: old, new: new)
      }
      .translationTask(appData.configuration) { session in
         do {
            let response = try await session.translate(textInput)
            textInput = response.targetText
         } catch {
            print("Error translating the text: \(error)")
         }
      }
   }
}