import SwiftUI

/// Modal Sheet allowing logged-in users to update their profile (nickname, email, phone).
struct EditProfileModalView: View {
    @Environment(\.dismiss) private var dismiss
    @ObservedObject var authManager: AuthManager = .shared
    
    @State private var usernameInput: String = ""
    @State private var emailInput: String = ""
    @State private var phoneInput: String = ""
    @State private var errorMessage: String?
    @State private var successToast: String?
    
    var body: some View {
        ZStack {
            Color.spaceBlack.ignoresSafeArea()
            
            VStack(spacing: 20) {
                // Header
                HStack {
                    Text("编辑个人资料")
                        .font(.system(size: 18, weight: .bold))
                        .foregroundStyle(Color.primary)
                    Spacer()
                    Button {
                        dismiss()
                    } label: {
                        Image(systemName: "xmark.circle.fill")
                            .font(.system(size: 22))
                            .foregroundStyle(Color.secondary.opacity(0.6))
                    }
                }
                .padding(.horizontal, 20)
                .padding(.top, 20)
                
                VStack(spacing: 14) {
                    inputSection(label: "用户昵称", icon: "person", text: $usernameInput, placeholder: "请输入新的用户昵称")
                    inputSection(label: "电子邮箱", icon: "envelope", text: $emailInput, placeholder: "绑定/修改电子邮箱")
                    inputSection(label: "手机号码", icon: "phone", text: $phoneInput, placeholder: "绑定/修改手机号码")
                    
                    if let error = errorMessage {
                        Text(error)
                            .font(.system(size: 12))
                            .foregroundStyle(Color.recordingRed)
                            .frame(maxWidth: .infinity, alignment: .leading)
                    }
                    
                    if let toast = successToast {
                        Text(toast)
                            .font(.system(size: 12))
                            .foregroundStyle(Color.green)
                            .frame(maxWidth: .infinity, alignment: .leading)
                    }
                }
                .padding(.horizontal, 20)
                .padding(.top, 10)
                
                Spacer()
                
                Button {
                    handleSave()
                } label: {
                    if authManager.isProcessing {
                        ProgressView()
                            .tint(Color.spaceBlack)
                    } else {
                        Text("保存修改")
                            .font(.system(size: 15, weight: .semibold))
                            .foregroundStyle(Color.spaceBlack)
                    }
                }
                .frame(maxWidth: .infinity)
                .padding(.vertical, 14)
                .background(Color.primary)
                .cornerRadius(8)
                .padding(.horizontal, 20)
                .padding(.bottom, 24)
                .disabled(authManager.isProcessing)
            }
        }
        .onAppear {
            if let user = authManager.currentUser {
                usernameInput = user.username
                emailInput = user.email ?? ""
                phoneInput = user.phoneNumber ?? ""
            }
        }
    }
    
    private func inputSection(label: String, icon: String, text: Binding<String>, placeholder: String) -> some View {
        VStack(alignment: .leading, spacing: 6) {
            Text(label)
                .font(.system(size: 12))
                .foregroundStyle(Color.secondary)
            
            HStack(spacing: 12) {
                Image(systemName: icon)
                    .font(.system(size: 14))
                    .foregroundStyle(Color.secondary)
                    .frame(width: 20)
                
                TextField(placeholder, text: text)
                    .font(.system(size: 14))
                    .autocapitalization(.none)
                    .disableAutocorrection(true)
            }
            .padding(.horizontal, 14)
            .padding(.vertical, 12)
            .background(Color.cardBackground.opacity(0.3))
            .businessBorder(cornerRadius: 8)
        }
    }
    
    private func handleSave() {
        errorMessage = nil
        successToast = nil
        
        authManager.updateProfile(
            username: usernameInput,
            email: emailInput,
            phoneNumber: phoneInput,
            avatarURL: nil
        ) { success, err in
            if success {
                successToast = "个人资料更新成功！"
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
                    dismiss()
                }
            } else {
                errorMessage = err ?? "保存修改失败"
            }
        }
    }
}
