//
//  ProfileView.swift
//  vibes
//
//  Created on 11/20/25.
//

import SwiftUI
import ConvexMobile
import Combine

struct ProfileView: View {
    @State private var currentUser: User?
    @State private var username: String = ""
    @State private var isLoading: Bool = true
    @State private var isSaving: Bool = false
    @State private var showSuccessMessage: Bool = false
    @State private var errorMessage: String?
    @State private var cancellable: AnyCancellable?
    
    var body: some View {
        ZStack {
            Constants.Colors.Background.primary
                .ignoresSafeArea()
            
            ScrollView {
                VStack(spacing: 24) {
                    // Header
                    HStack {
                        Text("Profile Settings")
                            .font(Constants.Typography.xLargeTitle)
                            .foregroundColor(Constants.Colors.Foreground.primary)
                        
                        Spacer()
                    }
                    .padding(.horizontal, 16)
                    .padding(.top, 24)
                    
                    if isLoading {
                        // Loading state
                        VStack(spacing: 16) {
                            ProgressView()
                                .progressViewStyle(CircularProgressViewStyle(tint: Constants.Colors.Foreground.primary))
                                .scaleEffect(1.2)
                            
                            Text("Loading profile...")
                                .font(Constants.Typography.mediumRegular)
                                .foregroundColor(Constants.Colors.Foreground.secondary)
                        }
                        .frame(maxWidth: .infinity)
                        .padding(.top, 60)
                    } else {
                        // Profile form
                        VStack(spacing: 16) {
                            // Email field (read-only)
                            VStack(alignment: .leading, spacing: 8) {
                                Text("Email")
                                    .font(Constants.Typography.smallTitle)
                                    .foregroundColor(Constants.Colors.Foreground.primary)
                                
                                HStack {
                                    Text(currentUser?.email ?? "")
                                        .font(Constants.Typography.mediumRegular)
                                        .foregroundColor(Constants.Colors.Foreground.secondary)
                                    
                                    Spacer()
                                }
                                .padding(16)
                                .background(Constants.Colors.Background.Fog.thin)
                                .clipShape(RoundedRectangle(cornerRadius: 12))
                            }
                            
                            // Username field (editable)
                            VStack(alignment: .leading, spacing: 8) {
                                Text("Username")
                                    .font(Constants.Typography.smallTitle)
                                    .foregroundColor(Constants.Colors.Foreground.primary)
                                
                                TextField("Enter username", text: $username)
                                    .font(Constants.Typography.mediumRegular)
                                    .foregroundColor(Constants.Colors.Foreground.primary)
                                    .padding(16)
                                    .background(Constants.Colors.Background.Fog.thin)
                                    .clipShape(RoundedRectangle(cornerRadius: 12))
                                    .textFieldStyle(PlainTextFieldStyle())
                                    .autocapitalization(.none)
                                    .disableAutocorrection(true)
                            }
                            
                            // Save button
                            Button(action: saveProfile) {
                                HStack(spacing: 8) {
                                    if isSaving {
                                        ProgressView()
                                            .progressViewStyle(CircularProgressViewStyle(tint: Constants.Colors.Foreground.primary))
                                            .scaleEffect(0.8)
                                    }
                                    
                                    Text(isSaving ? "Saving..." : "Save Changes")
                                        .font(Constants.Typography.mediumTitle)
                                        .foregroundColor(Constants.Colors.Foreground.primary)
                                }
                                .frame(maxWidth: .infinity)
                                .frame(height: 56)
                                .background(Constants.Colors.Accent.brand)
                                .clipShape(RoundedRectangle(cornerRadius: 100))
                            }
                            .disabled(isSaving || username.isEmpty)
                            .opacity(username.isEmpty ? 0.5 : 1.0)
                            .padding(.top, 8)
                            
                            // Success message
                            if showSuccessMessage {
                                HStack(spacing: 8) {
                                    Image(systemName: "checkmark.circle.fill")
                                        .foregroundColor(Constants.Colors.Accent.success)
                                    
                                    Text("Profile updated successfully")
                                        .font(Constants.Typography.small)
                                        .foregroundColor(Constants.Colors.Foreground.primary)
                                }
                                .padding(12)
                                .background(Constants.Colors.Background.Fog.thick)
                                .clipShape(RoundedRectangle(cornerRadius: 8))
                                .transition(.opacity)
                            }
                            
                            // Error message
                            if let errorMessage = errorMessage {
                                HStack(spacing: 8) {
                                    Image(systemName: "exclamationmark.circle.fill")
                                        .foregroundColor(Constants.Colors.Accent.error)
                                    
                                    Text(errorMessage)
                                        .font(Constants.Typography.small)
                                        .foregroundColor(Constants.Colors.Foreground.primary)
                                }
                                .padding(12)
                                .background(Constants.Colors.Background.Fog.thick)
                                .clipShape(RoundedRectangle(cornerRadius: 8))
                                .transition(.opacity)
                            }
                        }
                        .padding(.horizontal, 16)
                        
                        // Logout Button
                        Button(action: handleLogout) {
                            HStack(spacing: 8) {
                                Image(systemName: "rectangle.portrait.and.arrow.right")
                                    .font(.system(size: 16, weight: .medium))
                                
                                Text("Log Out")
                                    .font(Constants.Typography.mediumTitle)
                            }
                            .foregroundColor(Constants.Colors.Accent.error)
                            .frame(maxWidth: .infinity)
                            .frame(height: 56)
                            .background(Constants.Colors.Background.secondary)
                            .clipShape(RoundedRectangle(cornerRadius: 16))
                        }
                        .padding(.horizontal, 16)
                        .padding(.top, 32)
                    }
                    
                    Spacer()
                }
            }
        }
        .onAppear {
            loadCurrentUser()
        }
    }
    
    private func handleLogout() {
        Task {
            _ = await convex.logout()
        }
    }
    
    private func loadCurrentUser() {
        isLoading = true
        errorMessage = nil
        
        cancellable = convex.subscribe(to: "users:current", yielding: UserResponse?.self)
            .sink(
                receiveCompletion: { completion in
                    if case .failure(let error) = completion {
                        isLoading = false
                        errorMessage = "Failed to load profile: \(error.localizedDescription)"
                    }
                },
                receiveValue: { userResponse in
                    if let userResponse = userResponse {
                        currentUser = User(
                            id: userResponse._id,
                            email: userResponse.email,
                            username: userResponse.username
                        )
                        username = currentUser?.username ?? ""
                    }
                    isLoading = false
                }
            )
    }
    
    private func saveProfile() {
        Task {
            do {
                isSaving = true
                showSuccessMessage = false
                errorMessage = nil
                
                try await convex.mutation(
                    "users:updateUsername",
                    with: ["username": username]
                )
                
                // Update local user object
                if currentUser != nil {
                    currentUser?.username = username
                }
                
                isSaving = false
                showSuccessMessage = true
                
                // Hide success message after 3 seconds
                DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                    withAnimation {
                        showSuccessMessage = false
                    }
                }
            } catch {
                isSaving = false
                errorMessage = "Failed to save: \(error.localizedDescription)"
                
                // Hide error message after 5 seconds
                DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                    withAnimation {
                        errorMessage = nil
                    }
                }
            }
        }
    }
}

// MARK: - User Models
struct User {
    var id: String
    var email: String
    var username: String?
}

struct UserResponse: Decodable {
    let _id: String
    let email: String
    let username: String?
}

// MARK: - Preview
#Preview {
    ProfileView()
}

