//
//  RegistrationView.swift
//  VolnahubApp
//
//  Created by cheykrym on 09/06/2025.
//

import SwiftUI

struct RegistrationView: View {
    @ObservedObject var viewModel: LoginViewModel
    let onShowModePrompt: (() -> Void)?

    @State private var password: String = ""
    @State private var confirmPassword: String = ""
    @State private var inviteCode: String = ""

    @State private var isLoading: Bool = false
    @State private var showError: Bool = false
    @State private var errorMessage: String = ""
    @State private var isShowingTerms: Bool = false

    @FocusState private var focusedField: Field?

    private enum Field: Hashable {
        case username
        case password
        case confirmPassword
        case invite
    }

    private var isUsernameValid: Bool {
        let pattern = "^[A-Za-z0-9_]{3,32}$"
        return viewModel.passwordlessLogin.range(of: pattern, options: .regularExpression) != nil
    }

    private var isPasswordValid: Bool {
        password.count >= 8 && password.count <= 128
    }

    private var isConfirmPasswordValid: Bool {
        confirmPassword == password && !confirmPassword.isEmpty
    }

    private var isFormValid: Bool {
        isUsernameValid && isPasswordValid && isConfirmPasswordValid && viewModel.hasAcceptedTerms
    }

    init(viewModel: LoginViewModel, onShowModePrompt: (() -> Void)? = nil) {
        self._viewModel = ObservedObject(initialValue: viewModel)
        self.onShowModePrompt = onShowModePrompt
    }

    var body: some View {
        ScrollView(showsIndicators: false) {
            VStack(alignment: .leading, spacing: 24) {
                LoginTopBar(openLanguageSettings: openLanguageSettings, onShowModePrompt: keyboardDismissingModePrompt)

                Button(action: goBack) {
                    HStack(spacing: 6) {
                        Image(systemName: "arrow.left")
                        Text(NSLocalizedString("Назад", comment: ""))
                    }
                    .font(.footnote)
                    .foregroundColor(.blue)
                }

                VStack(alignment: .leading, spacing: 8) {
                    Text(NSLocalizedString("Регистрация", comment: "Регистрация"))
                        .font(.largeTitle).bold()
//                    Text(NSLocalizedString("Создайте логин и пароль. При желании добавьте инвайт.", comment: ""))
//                        .foregroundColor(.secondary)
                }

                Group {
                    VStack(alignment: .leading, spacing: 4) {
                        HStack(spacing: 8) {
                            Text("@")
                                .foregroundColor(.secondary)
                            TextField(NSLocalizedString("Введите логин", comment: "Логин"), text: $viewModel.passwordlessLogin)
                                .autocapitalization(.none)
                                .disableAutocorrection(true)
                                .focused($focusedField, equals: .username)
                        }
                        .padding()
                        .background(Color(.secondarySystemBackground))
                        .cornerRadius(12)

                        if !isUsernameValid && !viewModel.passwordlessLogin.isEmpty {
                            Text(NSLocalizedString("Логин должен быть от 3 до 32 символов (английские буквы, цифры, _)", comment: ""))
                                .foregroundColor(.red)
                                .font(.caption)
                        }
                    }

                    VStack(alignment: .leading, spacing: 4) {
                        SecureField(NSLocalizedString("Введите пароль", comment: "Пароль"), text: $password)
                            .autocapitalization(.none)
                            .focused($focusedField, equals: .password)
                            .padding()
                            .background(Color(.secondarySystemBackground))
                            .cornerRadius(12)
                            .onChange(of: password) { newValue in
                                if newValue.count > 128 {
                                    password = String(newValue.prefix(128))
                                }
                            }

                        if !isPasswordValid && !password.isEmpty {
                            Text(NSLocalizedString("Пароль должен быть от 8 до 128 символов", comment: ""))
                                .foregroundColor(.red)
                                .font(.caption)
                        }
                    }

                    VStack(alignment: .leading, spacing: 4) {
                        SecureField(NSLocalizedString("Подтвердите пароль", comment: ""), text: $confirmPassword)
                            .autocapitalization(.none)
                            .focused($focusedField, equals: .confirmPassword)
                            .padding()
                            .background(Color(.secondarySystemBackground))
                            .cornerRadius(12)
                            .onChange(of: confirmPassword) { newValue in
                                if newValue.count > 32 {
                                    confirmPassword = String(newValue.prefix(32))
                                }
                            }

                        if !isConfirmPasswordValid && !confirmPassword.isEmpty {
                            Text(NSLocalizedString("Пароли не совпадают", comment: ""))
                                .foregroundColor(.red)
                                .font(.caption)
                        }
                    }

                    TextField(NSLocalizedString("Инвайт-код (необязательно)", comment: ""), text: $inviteCode)
                        .autocapitalization(.none)
                        .disableAutocorrection(true)
                        .focused($focusedField, equals: .invite)
                        .padding()
                        .background(Color(.secondarySystemBackground))
                        .cornerRadius(12)
                }

                TermsAgreementCard(
                    isAccepted: $viewModel.hasAcceptedTerms,
                    openTerms: {
                        viewModel.loadTermsIfNeeded()
                        isShowingTerms = true
                    }
                )

                Button(action: registerUser) {
                    if isLoading {
                        ProgressView()
                            .frame(maxWidth: .infinity)
                            .padding()
                    } else {
                        Text(NSLocalizedString("Зарегистрироваться", comment: "Зарегистрироваться"))
                            .foregroundColor(.white)
                            .frame(maxWidth: .infinity)
                            .padding()
                    }
                }
                .background(isFormValid ? Color.blue : Color.gray.opacity(0.6))
                .cornerRadius(12)
                .disabled(!isFormValid)
            }
            .padding(.vertical, 32)
        }
        .padding(.horizontal, 24)
        .background(Color(.systemBackground).ignoresSafeArea())
        .contentShape(Rectangle())
        .onTapGesture { focusedField = nil }
        .alert(isPresented: $showError) {
            Alert(
                title: Text(NSLocalizedString("Ошибка регистрация", comment: "Ошибка")),
                message: Text(errorMessage),
                dismissButton: .default(Text(NSLocalizedString("OK", comment: "")))
            )
        }
        .fullScreenCover(isPresented: $isShowingTerms) {
            TermsFullScreenView(
                isPresented: $isShowingTerms,
                title: NSLocalizedString("Правила сервиса", comment: ""),
                content: viewModel.termsContent,
                isLoading: viewModel.isLoadingTerms,
                errorMessage: viewModel.termsErrorMessage,
                onRetry: {
                    viewModel.reloadTerms()
                }
            )
            .onAppear {
                if viewModel.termsContent.isEmpty {
                    viewModel.loadTermsIfNeeded()
                }
            }
        }
    }

    private func registerUser() {
        isLoading = true
        errorMessage = ""
        let trimmedLogin = viewModel.passwordlessLogin.trimmingCharacters(in: .whitespacesAndNewlines)
        viewModel.passwordlessLogin = trimmedLogin
        viewModel.registerUser(username: trimmedLogin, password: password, invite: inviteCode.isEmpty ? nil : inviteCode) { success, message in
            isLoading = false
            if success {
                viewModel.hasAcceptedTerms = false
            } else {
                errorMessage = message ?? NSLocalizedString("Неизвестная ошибка.", comment: "")
                showError = true
            }
        }
    }

    private func goBack() {
        focusedField = nil
        viewModel.hasAcceptedTerms = false
        withAnimation {
            viewModel.showPasswordlessRequest()
        }
    }

    private var keyboardDismissingModePrompt: (() -> Void)? {
        guard let onShowModePrompt else { return nil }
        return {
            focusedField = nil
            onShowModePrompt()
        }
    }

    private func openLanguageSettings() {
        guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
        UIApplication.shared.open(url)
    }
}


struct RegistrationView_Previews: PreviewProvider {
    static var previews: some View {
        let viewModel = LoginViewModel()
        viewModel.isLoading = false // чтобы убрать спиннер
        viewModel.isInitialLoading = false
        return RegistrationView(viewModel: viewModel, onShowModePrompt: nil)
    }
}
