import SwiftUI
#if canImport(UIKit)
import UIKit
#endif

struct FeedbackView: View {
    @State private var suggestion: String = ""
    @State private var submittedSuggestion: String? = nil
    @State private var isSubmitting: Bool = false
    @State private var showSubmissionMessage: Bool = false
    @FocusState private var isSuggestionFocused: Bool

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 20) {
                Text(NSLocalizedString("Какая вкладка вам нужна?", comment: ""))
                    .font(.title2)
                    .fontWeight(.semibold)

                Text(NSLocalizedString(
                    "Мы планируем заменить вкладку. Поделитесь, что бы вы хотели видеть здесь чаще всего.",
                    comment: ""
                ))
                .foregroundColor(.secondary)

                VStack(alignment: .leading, spacing: 12) {
                    Text(NSLocalizedString("Ваше предложение", comment: ""))
                        .font(.headline)

                    TextEditor(text: $suggestion)
                        .frame(minHeight: 120)
                        .padding(12)
                        .background(
                            RoundedRectangle(cornerRadius: 12)
                                .fill(Color(.systemGray6))
                        )
                        .overlay(
                            RoundedRectangle(cornerRadius: 12)
                                .stroke(Color(.systemGray4))
                        )
                        .overlay(
                            Group {
                                if suggestion.isEmpty {
                                    Text(NSLocalizedString("Например: закладки, друзья, активность...", comment: ""))
                                        .foregroundColor(.secondary)
                                        .padding(18)
                                        .allowsHitTesting(false)
                                }
                            }
                        )
                        .disableAutocorrection(true)
                        .focused($isSuggestionFocused)
                }

                Button(action: submitSuggestion) {
                    HStack {
                        if isSubmitting {
                            ProgressView()
                                .progressViewStyle(CircularProgressViewStyle())
                        }
                        Text(isSubmitting
                             ? NSLocalizedString("Отправляем...", comment: "")
                             : NSLocalizedString("(не работает) Отправить предложение", comment: ""))
                            .fontWeight(.semibold)
                    }
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(suggestionIsValid ? Color.accentColor : Color(.systemGray4))
                    .foregroundColor(.white)
                    .cornerRadius(14)
                }
                .disabled(!suggestionIsValid || isSubmitting)

                if let submittedSuggestion, showSubmissionMessage {
                    VStack(alignment: .leading, spacing: 8) {
                        Text(NSLocalizedString("Спасибо!", comment: ""))
                            .font(.headline)
                        Text(String(format: NSLocalizedString("Вы предложили: %@", comment: ""), submittedSuggestion))
                            .foregroundColor(.secondary)
                    }
                    .transition(.opacity)
                }

                Spacer(minLength: 24)

//                Text(NSLocalizedString(
//                    "Позже мы добавим отправку на сервер, чтобы собрать статистику, и расскажем о результатах в обновлениях.",
//                    comment: ""
//                ))
//                .font(.footnote)
//                .foregroundColor(.secondary)
            }
            .padding(.horizontal, 20)
            .padding(.vertical, 32)
        }
        .simultaneousGesture(
            TapGesture().onEnded {
                dismissKeyboardIfNeeded()
            }
        )
    }

    private var suggestionIsValid: Bool {
        !suggestion.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
    }

    private func submitSuggestion() {
        guard suggestionIsValid else { return }
        let trimmed = suggestion.trimmingCharacters(in: .whitespacesAndNewlines)

        dismissKeyboardIfNeeded()

        isSubmitting = true
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) { // имитируем сетевой вызов
            submittedSuggestion = trimmed
            suggestion = ""
            withAnimation {
                showSubmissionMessage = true
            }
            isSubmitting = false
        }
    }
}

private extension FeedbackView {
    func dismissKeyboardIfNeeded() {
        guard isSuggestionFocused else { return }
        isSuggestionFocused = false

#if canImport(UIKit)
        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
#endif
    }
}

struct FeedbackView_Previews: PreviewProvider {
    static var previews: some View {
        FeedbackView()
            .environmentObject(ThemeManager())
    }
}
