import Foundation
import ComposeApp
import Combine

/// ViewModel for user registration.
/// Calls APILayer directly for registration.
@MainActor
class RegisterViewModel: ObservableObject {
    // MARK: - Published Properties
    @Published var username: String = ""
    @Published var email: String = ""
    @Published var password: String = ""
    @Published var confirmPassword: String = ""
    @Published var isLoading: Bool = false
    @Published var errorMessage: String?
    @Published var isRegistered: Bool = false

    // MARK: - Private Properties
    private let dataManager: DataManagerObservable

    // MARK: - Initialization
    init(dataManager: DataManagerObservable = .shared) {
        self.dataManager = dataManager
    }

    // MARK: - Public Methods
    func register() {
        // Validation using ValidationRules
        if let error = ValidationRules.validateRequired(username, fieldName: "Username") {
            errorMessage = error.errorDescription
            return
        }

        if let error = ValidationRules.validateEmail(email) {
            errorMessage = error.errorDescription
            return
        }

        if let error = ValidationRules.validatePassword(password) {
            errorMessage = error.errorDescription
            return
        }

        if let error = ValidationRules.validatePasswordStrength(password) {
            errorMessage = error.errorDescription
            return
        }

        if let error = ValidationRules.validatePasswordMatch(password, confirmPassword) {
            errorMessage = error.errorDescription
            return
        }

        isLoading = true
        errorMessage = nil

        Task {
            do {
                let request = RegisterRequest(username: username, email: email, password: password, firstName: nil, lastName: nil)
                let result = try await APILayer.shared.register(request: request)

                if let success = result as? ApiResultSuccess<AuthResponse>, let response = success.data {
                    // APILayer.register() now handles:
                    // - Setting auth token in DataManager
                    // - Storing token in TokenManager
                    // - Initializing lookups

                    // Share token and API URL with widget extension
                    WidgetDataManager.shared.saveAuthToken(response.token)
                    WidgetDataManager.shared.saveAPIBaseURL(ApiClient.shared.getBaseUrl())

                    // Track successful registration
                    AnalyticsManager.shared.track(.userRegistered(method: "email"))

                    // Auth state is set AFTER sheets dismiss (via LoginView's
                    // sheet onDismiss callback). Setting isAuthenticated here while
                    // the RegisterView sheet is still presented would cause RootView
                    // to swap LoginView→MainTabView behind the UIKit sheet, leaving
                    // a stale view hierarchy.

                    self.isRegistered = true
                    self.isLoading = false
                } else if let error = ApiResultBridge.error(from: result) {
                    // Handle specific HTTP status codes
                    if let code = error.code?.intValue {
                        switch code {
                        case 409:
                            // Conflict - duplicate username or email
                            // The backend error message already contains the specific conflict
                            self.errorMessage = ErrorMessageParser.parse(error.message)
                        case 400:
                            // Bad request - validation errors
                            self.errorMessage = ErrorMessageParser.parse(error.message)
                        case 500...599:
                            self.errorMessage = "Server error. Please try again later."
                        default:
                            self.errorMessage = ErrorMessageParser.parse(error.message)
                        }
                    } else {
                        self.errorMessage = ErrorMessageParser.parse(error.message)
                    }
                    self.isLoading = false
                } else {
                    self.errorMessage = "Failed to create account"
                    self.isLoading = false
                }
            } catch {
                self.errorMessage = ErrorMessageParser.parse(error.localizedDescription)
                self.isLoading = false
            }
        }
    }

    func clearError() {
        errorMessage = nil
    }
}
